Reputation: 23
So I'm trying to set up a website for a school project and part of it requires obtaining user location and displaying it on a map. I've managed to get the user location using the geolocator api but can't seem to update the marker as even after getting new lat long it remains in the default location. Any help would be greatly appreciated :)
I've taken a default location (California) to display on loading the website (which it does successfully) and managed to get user location (verified using console to display results) but the code still displays the California marker.
<script type="text/javascript">
var latitude = 36.8;
var longitude = -119.4;
var currloc;
function getLoc() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = (Math.round(position.coords.latitude*100))/100;
longitude = (Math.round(position.coords.longitude*100))/100;
currloc = {lat: latitude, lng: longitude};
console.log("Geolocation supported");
console.log(latitude);
console.log(longitude);
});
}
else {
latitude = 0.0;
longitude = 0.0;
console.log("Geolocation not supported");
}
}
function mapInit() {
currloc = {lat: latitude, lng: longitude};
var map = new google.maps.Map(document.getElementById("map"), {zoom: 4, center: currloc, disableDoubleClickZoom: true,});
var mark = new google.maps.Marker({
position: currloc,
map: map,
title: latitude+', '+longitude
});
}
</script>
I would expect the marker to change as the initMap function's currloc values have changed however on the map it doesn't show the new location.
Upvotes: 2
Views: 35
Reputation: 46
getLoc() is asynchronous. Currloc changes after the callback is called. I am assuming you called mapInit synchronously. Call the marker inside the callback
Upvotes: 1