Reputation: 335
I'm currently working with a page that will eventually plot a series of markers (their data coming from a JSON object) onto a Google Map.
I can't seem to configure out a way of keeping the markers array filled. As outside the scope of the getJSON call, the array is empty.
var markers = [];
var map;
var mapOptions = {
center: new google.maps.LatLng(0.0, 0.0),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
$.getJSON("Home/GetLocations", function (data) {
for (index in data) addMarker(data[index]);
function addMarker(_data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(_data.lat, _data.lng),
map: map,
title: _data.name
});
markers.push(marker);
}
//markers = 3 at this point.
});
// markers = 0 at this point.
The reason i need the array to still be filled, is that i intend to create a hyperlink of each marker on the page, so that it can be clicked on and the map zooms to the correct marker. Ideally this would be a hyperlink with a javascript function call, this javascript function would be passed the selected hyperlink's marker index as a parameter, allowing me to go e.g
function zoomIn(selectedIndex) {
map.setCenter(markers[selectedIndex].getPosition());
}
But at this point, the markers array is blank, so no longer holds each marker.
If anyone could point me in the right direction that would be great. Thanks
Upvotes: 2
Views: 2970
Reputation: 1525
The function specified in the getJSON call will be called when getJSON completes, which is not necessarily when the code using the markers array will run. I think if you put the call to zoomIn (or whatever needs to use markers) inside the function specified in the getJSON call, markers will be filled when the time comes to use it. The key is that the markers array is being filled asynchronously, so you need to ensure the order in which your code executes.
If you are checking the markers array immediately following the getJSON call, don't. Check the markers array in the zoomIn function where it's being used.
Upvotes: 5
Reputation: 4372
Is all this code in the same scope? You will need to have this var markers = [];
in a global scope in order to have it accessible from all functions.
So do something like this:
var markers = [];
var map;
var mapOptions = {
center: new google.maps.LatLng(0.0, 0.0),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
function init(){
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
$.getJSON("Home/GetLocations", function (data) {
for (index in data) addMarker(data[index]);
function addMarker(_data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(_data.lat, _data.lng),
map: map,
title: _data.name
});
markers.push(marker);
}
});
}
function zoomIn(selectedIndex) {
map.setCenter(markers[selectedIndex].getPosition());
}
Then the array markers
will be available at a global scope.
Upvotes: 1