Reputation: 1934
I can't seem to add a markers to my maps. I am using Google Maps v.3 and Ruby on Rails.
Here's my JavaScript:
<script type="text/javascript">
var map;
function initialize()
{
var lat, lon, myOptions;
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude;
lon = position.coords.longitude;
myOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
},
function(error)
{
alert('Error: An error occur while fetching information from the Google API');
});
}
else
{
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
// Function for adding a marker to the page.
function addMarker(lat, lng) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
}
</script>
Here is the HTML page and how I call it:
<div id="maps">
<div id="map_canvas" style="width:100%; height:400px">
</div>
<script type="text/javascript">
initialize();
addMarker(46.4352,-80.9455);
</script>
Upvotes: 1
Views: 372
Reputation: 2303
It's because addMarker()
is being called before initialize()
has finished.
initialize()
needs to wait for a response from the geolocation api which means the map isn't initialized when you try and create the marker.
If you wrap addMarker inside callback and pass that to the initializing function which calls the callback function once a response is received then it should work as expected.
initialize(function() {
addMarker(46.4352,-80.9455);
});
function initilize(callback) {
navigator.geolocation.getCurrentPosition(function(position) {
// set up the map
callback();
});
}
Upvotes: 2