I'm using the Maps JavaScript API and am putting a map with center being in some set latitude and longitude. I'm trying to set the default coordinates to be the user's location in the end, but on testing certain set coordinates, the page only seems to change coordinates when the user deletes his/her cookies and refreshes the page. How can I make it so that the user does not have to delete their cookies to receive the latest coordinates from JavaScript?
My code that does not update as desired:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
Edit: I'm changing it manually and refreshing the page for now, but later I would automatically set location using
<div id="map" style="height: 400px; width: 100%;"></div>
<script>
var map;
var default_coords;
navigator.geolocation.getCurrentPosition(function(position) {
default_coords = {lat: position.coords.latitude, lng: position.coords.longitude};
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: default_coords,
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap" async defer></script>
The problem is that the map location does not change even if I change it in the code.
It looks like this is happening because of the fact that HTML5 Geolocation requires the user's explicit permission to get their location.
Therefore, you can't use the user's current location alone as the map's center. You need a fallback location in case the user (or their browser settings) does not give permission, or the browser itself does not support geolocation.
Try the code below:
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644}, // any hard-coded lat/lng
zoom: 8
});
navigator.geolocation.getCurrentPosition(function(position) {
var default_coords = {lat: position.coords.latitude, lng: position.coords.longitude};
map.setCenter(default_coords);
});
Hope this helps!