1

我使用 Google Maps API 将地址数据库保存在一个点中。

遇到一个问题,这是我无法决定的第三天。你能给我一些建议吗。

我循环遍历所有在地图上标记的点,其中使用 geotsoder.geoсode 识别并使用 ajax 在数据库中写入此地址。

例子:

function saveAddress(marker_points)
{
    var i = 0;
    id = 0;
    address = [];
    var count  = 0;
    points = [];
    for(i in marker_points) 
    {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode( {'address': marker_points[i]},function(results, status){
            address = results[0].formatted_address;
        });

    $.ajax({
        type: "POST",
        url: "/user.view.location.phone_id-{/literal}{$iPhoneId}{literal}.html",
        cache: false,
        data:  "address=" + address + "&location_point=" + marker_points[i],
        dataType: "html",
        async: false,
        timeout: 5000,
        success: function (data) {
        }
    }); 
}
}

但是在Ajax 中通过了最后一个点,即写在数据库中返回的最后一个地址和这个地址上的最后一个点。

你能告诉我可能是什么问题以及如何解决它,因为他已经尝试了所有选项,但它不起作用?

4

2 回答 2

0

我认为您的脚本有时可能会在从 geocoder.geocode 获得响应之前调用 ajax 方法。尝试将 $.ajax 方法放入

function(results, status){
    address = results[0].formatted_address;
}

所以你的代码片段看起来像:

var marker_points = ["50.463425,30.508120","50.465822,30.514380","50.465317,30.515609"];

for(i in marker_points) {   
       codeAndSendAddress(marker_points[i]);
}

function codeAndSendAddress(point){
    var mp = point.split(',');//Extract numbes from string
    var latLng =  new google.maps.LatLng(mp[0],mp[1]) // create latitude/logitude object


    geocoder.geocode( { 'latLng': latLng}, function(results, status) {
        if(status == google.maps.GeocoderStatus.OK) { make sure location was found

            var geocodedAddress = results[0].formatted_address;
            var geocodedLocationPoint = results[0].geometry.location;

            $.ajax({
                type: "POST",
                url: "/user.view.location.phone_id-{/literal}{$iPhoneId}{literal}.html",
                data: 'address='+geocodedAddress+
                '&geocoded_location_point='+geocodedLocationPoint+
                '&location_point='+point,
                timeout: 5000,
                success: function (data) {}
            });

        }
    });
}
于 2012-11-06T10:36:31.293 回答
0

您可以使用函数闭包将请求与响应相关联。

使用地理编码地址的示例:

它们在“i”上关闭的功能是:

function geocodeAddress(i) {
    geocoder.geocode({'address' : locations[i]},
       function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
             map.setCenter(results[0].geometry.location);
             createMarker(results[0].geometry.location, i);
          } else {
             alert('Geocode was not successful for the following reason: '
                    + status);
          }
    });
}     
于 2012-11-06T13:50:30.987 回答