谷歌地点获取经纬度

13

我正在使用自动完成方法来获取地点建议,当我点击要选择的位置时,我想提取放置在place.geometry.location下面的LatLng

Firebug Screenshot

根据我的观察,键ibjb会随着每个会话而改变。 我能否以可预测性的方式提取LatLng

$(document).ready(function() {

    var mapOptions = {
        center : new google.maps.LatLng(-33.8688, 151.2195),
        zoom : 13,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

    $('#searchTextField').bind('keydown keypress', function() {
        setTimeout(function() {
            var inputQuery = $('#searchTextField').val();

            if (inputQuery.length >= 2) {
                //console.log(inputQuery);

                /*
                var service = new google.maps.places.AutocompleteService();

                service.getPlacePredictions({
                    input : inputQuery
                }, callback);
                */

                var input = document.getElementById('searchTextField');
                var options = {
                    types : ['geocode']
                };

                var autocomplete = new google.maps.places.Autocomplete(input, options);

                // Acting on Selecting a place
                google.maps.event.addListener(autocomplete, 'place_changed', function() {
                    //infowindow.close();
                    var place = autocomplete.getPlace();

                    console.log(place);
                    console.log(place.formatted_address);
                    console.log(place.name);
                    console.log(place.geometry.location);
                    console.log(place.geometry.location[0]);

                    // Show the map to the current location selected
                    if (place.geometry.viewport) {
                        map.fitBounds(place.geometry.viewport);
                    } else {
                        map.setCenter(place.geometry.location);
                        map.setZoom(17);
                        // Why 17? Because it looks good.
                    }

                    var marker = new google.maps.Marker({
                        position : place.geometry.location,
                        map : map,
                        draggable : true,
                    });

                    $.each(place.geometry.location, function(key, value) {
                        console.log(key + ": " + value);
                    }); 
                });
            }

        }, 0);

    });
});
1个回答

44

place.geometry.location 是一个 LatLng,因此您可以调用它的 .lat().lng() 方法。

var location = place.geometry.location;
var lat = location.lat();
var lng = location.lng();

你会发现这些方法在检查该对象时是存在的。
不要使用未记录的属性,例如你发现的ib和jb。谷歌使用Closure Compiler或类似工具编译Maps API,生成私有属性和变量的随机名称。

我正在使用Places Web服务API,如何从响应中获取纬度和经度? - moein rahimi
这里的place变量是什么?我遇到了一个错误。 - M.suleman Khan
当使用自动完成类时,您可以使用以下代码获取变量 place = autocomplete.getPlace(); - infomasud

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接