I am new to Javascript and Google Maps and I am trying to add a marker to my map using the information provided on the Google Developers website. Although the map displays as it should on the current position and I am getting no errors on the Javascript console, for some reason the marker is still not showing up. Any ideas on why this is happening? Thanks in advance.
Here is my code:
function initialize() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
// Browser doesn't support Geolocation
else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
initialLocation = siberia;
}
map.setCenter(initialLocation);
}
var marker = new google.maps.Marker({
position: initialLocation,
title:"You are here!"
});
// should add the marker to the map
marker.setMap(map);
};
The geolocation service is asynchronous. You need to use the coordinates inside its callback function. Hard to tell from what you posted which path the geolocation is taking, here is code that would do it if it succeeds.