从名称或邮政编码获取纬度和经度-谷歌API

Get latitude and longitude from name or zipcode - google API

本文关键字:经度 谷歌 API 纬度 获取 邮政编码      更新时间:2023-10-21

我已经编辑了下面的代码,并放入了完整的JS。我正在尝试提取一个靠近给定邮政编码或城市的地方列表。我的第一步是取邮政编码或城市名称,得到坐标,然后得到地点列表。我得到以下错误"无法调用未定义的方法'geocode'"&"无法读取null的属性'offsetWidth'"如有任何帮助,我们将不胜感激。

    var placesList;
    var geocoder;
    var map;
    function initialize() {
        map = new google.maps.Map(document.getElementById('map'));
        geocoder = new google.maps.Geocoder();
    }
    function getLatLng(address, callback) {
        geocoder.geocode({
            address: address
        }, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                var location = new google.maps.LatLng(result.lat(), result.lng());                    
                map.setCenter(location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: location
                });
                callback(location);
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    getLatLng('14235', function (latLngLocation) {
        var pyrmont = latLngLocation;
        var request = {
            location: pyrmont,
            radius: 5000,
            types: ['park', 'zoo']
        };
        placesList = document.getElementById('places');
        var service = new google.maps.places.PlacesService(map);
        service.nearbySearch(request, callback);
        var request1 = {
            reference: place.reference
        };
        service.getDetails(request1, createMarkers);
        function callback(results, status, pagination) {
            if (status != google.maps.places.PlacesServiceStatus.OK) {
                return;
            } else {
                for (var i = 0; i < results.length; i++) {
                    var markerPlace = results[i];
                    createMarkers(markerPlace, status);
                }
                if (pagination.hasNextPage) {
                    var moreButton = document.getElementById('more');
                    moreButton.disabled = false;
                    google.maps.event.addDomListenerOnce(moreButton, 'click',
                        function () {
                            moreButton.disabled = true;
                            pagination.nextPage();
                        });
                }
            }
        }

        function createMarkers(place, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                var bounds = new google.maps.LatLngBounds();
                var image = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };
                var marker = new google.maps.Marker({
                    map: map,
                    icon: image,
                    title: place.name,
                    position: place.geometry.location
                });
                placesList.innerHTML += '<li>' + place.name + '<br>' +
                    (place.formatted_address ? place.formatted_address : place.vicinity) + '</li>';
                bounds.extend(place.geometry.location);
                map.fitBounds(bounds);
            }
        }
    });
    google.maps.event.addDomListener(window, 'load', initialize);

您的地址不是字符串,而是一个数字:

var address = 14235;

API希望GeocoderRequest中的"地址"是一个类似于邮政地址的字符串。如果您希望它是一个字符串,请将其括在引号中(尽管我不确定您希望地理编码器为单个数字返回什么):

var address = "14235";

如果你给地理编码器一些看起来更像完整地址的东西,它会更好地工作。

地理编码器的异步性质也有问题(常见问题解答),不能返回异步函数的结果,需要在回调函数中使用它。

您必须理解的是geocode API是异步的;您正试图在pyrmont准备就绪之前将结果变量分配给它。为了实现你想要的,你需要使用回调。此外,你在处理latLng归因时还有其他一些问题。不管怎样,我认为你的代码应该是这样的:

var map, geocoder; // global vars
// retain your initialize function
function initialize() {
  map = new google.maps.Map(document.getElementById('map'), options);
  geocoder = new google.maps.Geocoder();
}
// but separate out your code into a new function that accepts an address
// and a callback function.
function getLatLng(address, callback) {
   geocoder.geocode({ address: address }, function (results, status) {
     if (status === google.maps.GeocoderStatus.OK) {
       // assign a new Google latLng object to `location`
       var location = new google.maps.LatLng(result.lat(), result.lng();
       // set the center of the map and position using the latlng object
       map.setCenter(location);
       var marker = new google.maps.Marker({
         map: map,
         position: location;
       });
       // call the callback with the latlng object as a parameter.
       callback(location);
     } else {
       alert('Geocode was not successful for the following reason: ' + status);
     }
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
// call the `getLatLng` function with an address and a callback function
getLatLng('14235', function (latLngLocation) {
  var pyrmont = latLngLocation;
});