Question:
We need to parse the coordinates of the ski resorts by name. Using gmlocalsearch.js from Google API
var map;
var resorts = [];
var grespoints = [];
geocoder = new GClientGeocoder();
function MyGRes(id,title,lat,lon,adr){
this.id = id;
this.title = title;
this.lat = lat;
this.lon = lon;
this.adress = adr;
}
//объект для поиска, чтобы у него сделать свою callback-функцию
function MySearchRes(id,title){
this.id = id;
this.title = title;
}
//callback-функция у каждого своя. вот тут this ничего не выдает
MySearchRes.prototype.searchComplete = function (response){
if (!response || response.Status.code != 200) {
//alert("Status Code:" + response.Status.code);
} else {
place = response.Placemark[0];
var lat = place.Point.coordinates[1];
var lon = place.Point.coordinates[0];
var adress = place.adress;
grespoints.push(new MyGRes(this.id,this.title,lat,lon,adress));
}
}
function initialize() {
// кусок из джанго шаблона, если вкратце, то просто цикл, который в js-код вставит 2400*2 строк, раньше без var делал, тут уже шаманю, хотя конечно без var Надо делать я думаю
{% for item in resorts %}
var serobj{{forloop.counter0}} = new MySearchRes({{item.id}},"{{item.title|safe}}");
resorts.push(serobj{{forloop.counter0}});
{% endfor %}
}
// сама функция которая поиск делает
function addMarkers() {
for ( var i = 0;i<resorts.length;i++)
{
geocoder.getLocations(
resorts[i].title,
resorts[i].searchComplete
);
}
}
The bottom line is that when getLocations is called, the result asynchronously arrives in the callback, so I had to create my own object for each one in order to write the result and specify an id for it, so that later all this can be transferred to the base.
For some reason, this does not pass in searchComplete. I've already done such things, and this did not bode well, but here it is … by the way, I created MyGRes because the same this is not visible, it adds a DOM object to the grespoints array. PS I didn't put anything into separate files, since it doesn't matter, right? =)
Answer:
var initialize = function() {
{% for item in resorts %}
addMarker({{item.id}}, "{{item.title|safe}}");
{% endfor %}
}
var addMarker = function(id, title) {
geocoder.getLocations(
title,
function (response){
if (!response || response.Status.code != 200) {
//alert("Status Code:" + response.Status.code);
} else {
place = response.Placemark[0];
grespoints.push({
id: id,
title: title,
lat: place.Point.coordinates[1],
lng: place.Point.coordinates[0],
address: place.address
});
}
}
);
}