Вопрос

I am trying to add a GeoJSON layer to Google Maps (v3) by doing the following:

imageActive = {
    url: "images/target_red.png",
    origin: new google.maps.Point(0,0),
    anchor: new google.maps.Point(11, 11),
} // ACTIVE marker image

jQuery.getJSON('home/gcpts/geojson.php', function(data){
    points = map.data.addGeoJson(data);
    console.log(points); //this works
});

map.data.setStyle({
  clickable: true,
  draggable: false,
});

map.data.addListener('click', function(event){
  setActiveImage(event);
})

function setActiveImage(event){
  for(var i = 0;i<points.length;i++){ //can't read "length" of undefined
    points[i].revertStyles();
  }
  map.data.overrideStyle(event.feature, {
    icon: imageActive,
  });
}

However when I try to iterate through the "points" variable, I can't seem to "see" it. I mainly get undefined, or if I try to call the length of points (points.length), then it doesn't exist.

If I console.log(points) within the jQuery function, then I can see all of the features within the variable. If I place it on the outside, then I can't see it. Is there something I am missing about the scope?

It's my hope that I can set a "click" event and use event.feature to overrideStyle. Then when a different feature is clicked, then the style is removed from the other geoJson features and overrides the newly clicked feature.

It seems that this should work fine, but I can't seem to figure out how to iterate through the features.

Thanks!

(Also, I am using jQuery in "No conflict" mode...)

Это было полезно?

Решение

All of your variables are globally scoped because you aren't using the var keyword. It seems likely that some other script is looking for a points variable and overwrites yours. Assuming your code is already wrapped up in some kind of function (such as a jQuery ready handler), you may solve your problem by just using var. I'd add this line of code before you call getJSON():

var points = [];

Другие советы

The previous answer noted you need to ensure your "points" variable is scoped appropriately, but a better answer is that you don't need that variable at all: Since you are using map.data you can just use that directly to access your features, using something like:

map.data.foreEch(function(feature) {console.log(feature);})

Note of course your "map" variable must be appropriately scoped.

Additionally, you also don't need to use jQuery -- you can just load the data using map.data.loadGeoJson(theUrl) which will do the ajax for you

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top