Get LatLng from Zip Code - Google Maps API

前端 未结 6 719
我在风中等你
我在风中等你 2020-12-04 09:09

All I want is some simple example code that shows me how to obtain a latlng element from an inputted zip code OR a city/state.

6条回答
  •  醉酒成梦
    2020-12-04 09:47

    This is just an improvement to the previous answers because it didn't work for me with some zipcodes even when in https://www.google.com/maps it does, I fixed just adding the word "zipcode " before to put the zipcode, like this:

    function getLatLngByZipcode(zipcode) 
    {
        var geocoder = new google.maps.Geocoder();
        var address = zipcode;
        geocoder.geocode({ 'address': 'zipcode '+address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                alert("Latitude: " + latitude + "\nLongitude: " + longitude);
            } else {
                alert("Request failed.")
            }
        });
        return [latitude, longitude];
    }

提交回复
热议问题