简体   繁体   中英

Reload points on a Map in using the Google Maps API v3

I'm trying to reload points on a map based on when someone clicks a button.

I have a couple json objects saved in memory, "data" and "data2". The following code takes the "data2" JSON file and sets it equal to the "data" JSON file and then triggers a map reload event.

   dataholder = data
    function myFunction() {
      data = dataholder
      window.data = data2;
      google.maps.event.trigger(map, 'resize');
    }

Currently, the map won't reload with the new set of data. However, I am not getting any error messages.

There's no map reload event. The resize event, when it comes from a window resize, will at most recalculate the map bounds and reproject the existing features (markers, polylines, polygons). For this case in particular, I don't think that manually triggering the resize event will have any effect.

In second place, you say you have two json files, but your code suggest you instead have two json objects already in memory (meaning you don't need to perform aditional requests to retrieve the value of data2). The rest of the answer will assume that.

If your original collection of markers came from "data", which is a collection of LatLng pairs, and you want to replace the markers for the contents of "data2" the process would be:

1.- Push the markers into an object where you can find them later on

var markers=[];
for(onemarker in data) {
    var newmarker=new google.maps.Marker({map: map, position: new google.maps.LatLng({onemarker.lat, onemarker.lng}) });
    markers.push(newmarker);
}

2.- When you want to replace the markers, first purge the markers array

while(markers.length) {
     var oldmarker=markers.pop();
     oldmarker.setMap(null);
};

3.- Fill the markers array with the data from the data2 object

for(onemarker in data2) {
    var newmarker=new google.maps.Marker({map: map, position: new google.maps.LatLng({onemarker.lat, onemarker.lng}) });
    markers.push(newmarker);
}

For this kind of markers, as for the regular features, there's no instantaneous binding between the object and the underlying data. This is slightly different for the new google.maps.Data() layer for which you can skip the iteration and just feed it a geoJSON array. You still need to have an object to store the current markers, or else you won't have a way to access them when you want to remove them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM