我遇到谷歌地图API v3的问题,让我的听众提供结果。
我在这里添加了一个jsFiddle http://jsfiddle.net/f2DqW/4/
谁能告诉我我做错了什么?
当您点击一个标记时,我希望它从地址(很快就会有更多信息)中获取我的邮政编码并在屏幕上回显。最终我想要一个弹出窗口,但现在这并不重要。
我的代码是:
var geocoder;
var map;
function codeAddress() {
var address = 'SW3, United Kingdom';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function initialize() {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=SW3, United Kingdom', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
$('#latId').val(p.lat);
$('#latId2').val(p.lng);
});
var lat = $('#latId').val();
var lng = $('#latId2').val();
var map;
var elevator;
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(lat,lng),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['SW3', 'SW2', 'SW1'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'test'
});
google.maps.event.addListener(marker, 'click', function() {
alert(addresses[x]);
map.setCenter(marker.getPosition());
});
marker.setMap(map);
});
}
}
非常感谢提前。
答案 0 :(得分:0)
这是一个经典之作:变量x不会保留单击标记时您期望的值。它保留address.length。我会做那样的事情:
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, (function(address) { return function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'test'
});
google.maps.event.addListener(marker, 'click', function() {
alert(address);
map.setCenter(marker.getPosition());
});
marker.setMap(map);
};})(addresses[x]));
答案 1 :(得分:0)
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=' + addresses[x] + '&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'test'
});
google.maps.event.addListener(marker, 'click', function () {
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$.each(results[0].address_components, function (i, item) {
if (item.types[0] == 'postal_code') {
alert(item.long_name);
}
});
}
});
map.setCenter(marker.getPosition());
});
marker.setMap(map);
});
}
}