adding markers to existing map

1,975 views
Skip to first unread message

Morten

unread,
Aug 20, 2010, 6:51:17 PM8/20/10
to Google Maps JavaScript API v3
Upon page load I load and show a Google Map:

var latlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);

From within a select box's onchange handler I get location json and
would like to add these locations to the map.

How can I reference the map without the re-initializing part?

Something like:
var map = google.maps.Map(document.getElementById("map_canvas"));
$.each(locationCollection, function (i) {

var location = new google.maps.LatLng(this.LocationLat,
this.LocationLong);
var marker = new google.maps.Marker({
position: location,
map: map,
title: this.LocationName
});

});

joe

unread,
Aug 21, 2010, 8:19:49 AM8/21/10
to Google Maps JavaScript API v3
I think in this block of code :
var marker = new google.maps.Marker({
position: location,
map: map,
title: this.LocationName
});

the "map" var you declared back in the initiation is may not be
available in this scope. You can either declare "map" as a global or
put it into an object literal.

I wrote some example code http://www.joelee.me.uk/sampleCode/2010/googleMapsV3markersClearExample.html
Two things to note :
- "var mapStuff =" near the top is the code declaring the mapStuff as
an object literal
- "function addPubToMap" sees the code passing the mapStuff.theMap
into the parameter map parameter of the marker object

Hope that helps
Reply all
Reply to author
Forward
0 new messages