0

I have an array of javascript elements. Each element contains an address and a unique id.

var elements = 
[
    {
      id: 1, 
      address: "address1"
    },

    {
      id: 2, 
      address: "address2"
    }
];

Element addresses are geocoded and resulting markers are displayed in a Google Map, as indicated in this post.

for (var i = 0; i < elements.length; i++) {
    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+elements[i].address+'&sensor=false', null, function (data) {
        // add marker to map
        console.log(data.results[0]);
    });
}

Now my goal is to associate each marker with the proper request. For example, suppose that the first geocoding (id=1) results in a marker positioned at (lat: 15.0526206, lng: 19.6929845). I would like to find a way to associate this marker with id=1 element.

I've tried to log data result (see snippet above), but unfortunately it doesn't help (formatted_address is similar to original element address but formatted differently, so string comparion is not feasible). How can I do?

Community
  • 1
  • 1
Giorgio
  • 1,940
  • 5
  • 39
  • 64

1 Answers1

1

You'll need to create closures:

for (var i = 0; i < elements.length; i++) {
    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=' +
               encodeURIComponent(elements[i].address), 
               null, 
              (function(element){
                return function(data){
                console.log(element.id,data.results[0]);
                }  
              }(elements[i])));
}

But for clientside geocode-requests you should use the method of the javascript-API(requesting the webservice may fail, because it's not guaranteed that the appropriate headers will be sent)

var geocoder=new google.maps.Geocoder();  
for (var i = 0; i < elements.length; i++) {
    geocoder.geocode({address:elements[i].address}, 
    (function(element){
      return function(data){
        console.log(element.id,data[0]);
      }  
    }(elements[i])));
}
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • I actually started from javascript API, but I soon ran into `OVER_QUERY_LIMIT` issue (cited in the question I've posted). So, this is because I preferred to adopt the proposed `getJSON` method. I'll give a try to your solution, but at least +1 for `encodeURIComponent`, I didn't considered it. – Giorgio Mar 07 '15 at 10:40
  • requesting the webservice will not solve the `OVER_QUERY_LIMIT`, the limits are the same for both request-types. You'll need a delay between the requests(250ms should be enough to bypass the limit of 5 requests per second) – Dr.Molle Mar 07 '15 at 10:42
  • http://stackoverflow.com/questions/19640055/multiple-markers-google-map-api-v3-from-array-of-addresses-and-avoid-over-query/21398675#21398675 should be OK, but increase the `delay`. The current limit seems to be 5 per second(it previously has been 10 per second), a delay of 100 would allow 10 per second. – Dr.Molle Mar 07 '15 at 10:49