从谷歌地图API反向地理编码

时间:2012-11-06 10:24:59

标签: google-maps jquery

我使用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中传递了最后一点,即在数据库中写入了返回的最后一个地址以及该地址的最后一个点。

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

2 个答案:

答案 0 :(得分: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) {}
            });

        }
    });
}

答案 1 :(得分:0)

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

Example using geocoded addresses:

它们在“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);
          }
    });
}