[英]Google Maps: get lat/lng from geocoded postcode
我目前正在使用對象的地址在地圖上繪制多個點。 程序在對象上循環,對地址進行地址geocodes
,並為每個位置繪制一個標記。
我遇到的問題是,當用戶單擊列表中的某個位置時,地圖將平移到該位置。 該API具有panTo()
函數,該函數接受lat, lng
值,但是地理編碼函數的結果(即results[0].geometry.location
)在其外部不可用。
題
我如何以某種方式從結果中檢索lat, lng
,也許將其附加到現有數據對象中,並在函數外使用它們,以便能夠在panTo()
函數中使用它們?
[經/緯度值在html data
屬性中輸出]
點擊處理程序
$('.place').on('click', function() {
$this = $(this);
lat = $this.data('lat');
lng = $this.data('lng');
map.panTo(new google.maps.LatLng(lat, lng));
});
數據
var locations = [
{
id: 'place1',
postcode: 'B1 1AA'
},
{
id: 'place2',
postcode: 'CB9 8PU'
}
];
碼
for (i = 0; i < locations.length; i++) {
geocoder.geocode({'address': locations[i].postcode}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
} else {
console.log('Geocode was not successful ' + status);
}
}); // end geocode
$(places).append(
'<li class="place" data-id="'+locations[i].id+'" data-lat="<!--lat to go here-->" data-lng="<!--lng to go here-->">'+
'<div class="place-wrap">'+
'<h2>'+locations[i].name+'</h2>'+
'<p class="territory">'+locations[i].territory+'<p>'+
'</div>'+
'</li>'
);
} // end for
快去 IIFE用來封裝索引,因此,由於地理編碼的異步特性,您不必一直訪問locations
數組的最后一個索引。
for (i = 0, l = locations.length; i < l; i++) {
(function(i) { // index passed in as parameter
geocoder.geocode({ address: locations[i].postcode }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
$('#places').append(
'<li class="place" data-id="' + locations[i].id + '" data-lat="' + results[0].geometry.location.lat() + '" data-lng="' + results[0].geometry.location.lng() + '">' +
'<div class="place-wrap">' +
'<h2>' + locations[i].name + '</h2>' +
'<p class="territory">' + locations[i].territory + '<p>'+
'</div>' +
'</li>'
);
} else {
console.log('Geocode was not successful ' + status);
}
});
}(i)); // index passed in to IIFE
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.