I'm working with Google Maps JS API. I'm trying to set a marker at the center of my map. I'm using the currLocation
variable to hold the current location. The currLocation
variable has value within the inline private method ( Section 1), but it is null when I want to set a marker(Section 2).
Stackoverflow had lot of solutions for "Unable to set value to global variable", but I couldn't solve my issue with their reference.
Any help would be appreciated.
function initMap() {
var currLocation = null;
var defaultCenter = { lat: 34.397, lng: 150.644 };
//Set Map properties
var map = new google.maps.Map(document.getElementById('gmap'), {
scrollwheel: true,
zoom: 10
});
//Get Current Location - Section 1
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
currLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(currLocation);
});
}
else {
map.setCenter(defaultCenter);
}
//Put marker on the current location - Section 2
var marker = new google.maps.Marker({
position: currLocation,
map: map
});
}