Javascript 使用 Google Autocomplete API 根据位置名称获取纬度和经度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3490622/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get latitude and longitude based on location name with Google Autocomplete API
提问by Chandra
I have a textbox in my page which gets a location name and button with text getLat&Long. Now on clicking my button I have to show an alert of latitudeand longitudeof the location in the textbox. Any suggestion?
我的页面中有一个文本框,它获取位置名称和带有文本的按钮getLat&Long。现在,在我的点击按钮,我必须表明的警报latitude,并longitude在文本框的位置。有什么建议吗?
回答by RedBlueThing
You can use the Google Geocoder servicein the Google Maps APIto convert from your location name to a latitude and longitude. So you need some code like:
您可以使用谷歌地理编码服务的在谷歌地图API从您的位置名转换为纬度和经度。所以你需要一些代码,如:
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK)
  {
      // do something with the geocoded result
      //
      // results[0].geometry.location.latitude
      // results[0].geometry.location.longitude
  }
});
Update
更新
Are you including the v3 javascript API?
您是否包括 v3 javascript API?
<script type="text/javascript"
     src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false">
</script> 
回答by Ariel
I hope this can help someone in the future.
我希望这可以帮助将来的某个人。
You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:
你可以使用谷歌地理编码 API,如前所述,我最近不得不做一些工作,我希望这会有所帮助:
<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script type="text/javascript">
        function initialize() {
        var address = (document.getElementById('my-address'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }
        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
      });
}
function codeAddress() {
    geocoder = new google.maps.Geocoder();
    var address = document.getElementById("my-address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      alert("Latitude: "+results[0].geometry.location.lat());
      alert("Longitude: "+results[0].geometry.location.lng());
      } 
      else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
google.maps.event.addDomListener(window, 'load', initialize);
        </script>
    </head>
    <body>
        <input type="text" id="my-address">
        <button id="getCords" onClick="codeAddress();">getLat&Long</button>
    </body>
</html>
Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.
现在这还有一个自动完成功能,您可以在代码中看到它,它从输入中获取地址并在键入时由 API 自动完成。
Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).
一旦你有你的地址点击按钮,你就会根据需要通过警报获得结果。另请注意,这使用最新的 API 并加载“地点”库(调用 API 时使用“库”参数)。
Hope this helps, and read the documentation for more information, cheers.
希望这会有所帮助,并阅读文档以获取更多信息,干杯。
Edit #1: Fiddle
编辑#1:小提琴
回答by Sujeet
http://maps.googleapis.com/maps/api/geocode/OUTPUT?address=YOUR_LOCATION&sensor=true
http://maps.googleapis.com/maps/api/geocode/OUTPUT?address=YOUR_LOCATION&sensor=true
OUTPUT = json or xml;
输出 = json 或 xml;
for detail information about google map api go through url:
有关 google map api 的详细信息,请访问 url:
http://code.google.com/apis/maps/documentation/geocoding/index.html
http://code.google.com/apis/maps/documentation/geocoding/index.html
Hope this will help
希望这会有所帮助
回答by ducnguyenvn
The below is the code that i used. It's working perfectly.
下面是我使用的代码。它工作得很好。
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
    if (status == google.maps.GeocoderStatus.OK) {              
        var myLatLng = results[0].geometry.location;
        // Add some code to work with myLatLng              
    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }
});
Hope this will help.
希望这会有所帮助。
回答by Ashish Chaturvedi
I hope this will be more useful for future scope contain auto complete Google API feature with latitude and longitude
我希望这对未来的范围更有用,包含带有纬度和经度的自动完成 Google API 功能
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();  
Complete View
完整视图
<!DOCTYPE html>
<html>
    <head>
    <title>Place Autocomplete With Latitude & Longitude </title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
#pac-input {
    background-color: #fff;
    padding: 0 11px 0 13px;
    width: 400px;
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
    text-overflow: ellipsis;
}
#pac-input:focus {
    border-color: #4d90fe;
    margin-left: -1px;
    padding-left: 14px;  /* Regular padding-left + 1. */
    width: 401px;
}
}
</style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
    <script>
  function initialize() {
        var address = (document.getElementById('pac-input'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }
        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
        /*********************************************************************/
        /* var address contain your autocomplete address *********************/
        /* place.geometry.location.lat() && place.geometry.location.lat() ****/
        /* will be used for current address latitude and longitude************/
        /*********************************************************************/
        document.getElementById('lat').innerHTML = place.geometry.location.lat();
        document.getElementById('long').innerHTML = place.geometry.location.lng();
        });
  }
   google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    </head>
    <body>
<input id="pac-input" class="controls" type="text"
        placeholder="Enter a location">
<div id="lat"></div>
<div id="long"></div>
</body>
</html>
回答by user28864
I would suggest the following code, you can use this <script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>to get the latitude and longitude of a location, although it may not be so accurate however it worked for me;
我建议使用以下代码,您可以使用它<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>来获取位置的纬度和经度,尽管它可能不那么准确,但对我有用;
code snippet below
下面的代码片段
<!DOCTYPE html>
<html>
<head>
<title>Using Javascript's Geolocation API</title>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="mapContainer"></div> 
<script type="text/javascript">
        var lat = geoip_latitude();
        var long = geoip_longitude();
        document.write("Latitude: "+lat+"</br>Longitude: "+long);
</script> 
</body>
</html> 
回答by N?s????? ?
Enter the location by Autocomplete and rest of all the fields:  latitude and Longititude values get automatically filled.
Replace API KEY with your Google API key 
通过自动完成和其余所有字段输入位置:纬度和经度值会自动填充。
将 API KEY 替换为您的 Google API 密钥
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
</head>
<body>
<textarea placeholder="Enter Area name to populate Latitude and Longitude" name="address" onFocus="initializeAutocomplete()" id="locality" ></textarea><br>
<input type="text" name="city" id="city" placeholder="City" value="" ><br>
<input type="text" name="latitude" id="latitude" placeholder="Latitude" value="" ><br>
<input type="text" name="longitude" id="longitude" placeholder="Longitude" value="" ><br>
<input type="text" name="place_id" id="location_id" placeholder="Location Ids" value="" ><br>
<script type="text/javascript">
  function initializeAutocomplete(){
    var input = document.getElementById('locality');
    // var options = {
    //   types: ['(regions)'],
    //   componentRestrictions: {country: "IN"}
    // };
    var options = {}
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      var place = autocomplete.getPlace();
      var lat = place.geometry.location.lat();
      var lng = place.geometry.location.lng();
      var placeId = place.place_id;
      // to set city name, using the locality param
      var componentForm = {
        locality: 'short_name',
      };
      for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType]) {
          var val = place.address_components[i][componentForm[addressType]];
          document.getElementById("city").value = val;
        }
      }
      document.getElementById("latitude").value = lat;
      document.getElementById("longitude").value = lng;
      document.getElementById("location_id").value = placeId;
    });
  }
</script>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?libraries=places&key=API KEY"></script>
<script src="https://fonts.googleapis.com/css?family=Roboto:300,400,500></script>

