使用 javascript 获取我当前的地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14580715/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:17:19  来源:igfitidea点击:

Get my current address using javascript

javascriptjquerygoogle-mapsgeolocation

提问by tim peterson

I was interested in getting my current address using Javascript and just figured this out by assembling some other SO threads (1,2) so wanted to post this question and answer.

我有兴趣使用 Javascript 获取我当前的地址,并且只是通过组装其他一些 SO 线程(12)来解决这个问题,所以想发布这个问题和答案。

Please see answer below.

请看下面的回答。

回答by tim peterson

Here's the HTML:

这是 HTML:

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<p id='latitudeAndLongitude'></p>
<p id='address'></p> 

Here's the JS:

这是JS:

var latitudeAndLongitude=document.getElementById("latitudeAndLongitude"),
location={
    latitude:'',
    longitude:''
};

if (navigator.geolocation){
  navigator.geolocation.getCurrentPosition(showPosition);
}
else{
  latitudeAndLongitude.innerHTML="Geolocation is not supported by this browser.";
}

function showPosition(position){ 
    location.latitude=position.coords.latitude;
    location.longitude=position.coords.longitude;
    latitudeAndLongitude.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
    var geocoder = new google.maps.Geocoder();
    var latLng = new google.maps.LatLng(location.latitude, location.longitude);

 if (geocoder) {
    geocoder.geocode({ 'latLng': latLng}, function (results, status) {
       if (status == google.maps.GeocoderStatus.OK) {
         console.log(results[0].formatted_address); 
         $('#address').html('Address:'+results[0].formatted_address);
       }
       else {
        $('#address').html('Geocoding failed: '+status);
        console.log("Geocoding failed: " + status);
       }
    }); //geocoder.geocode()
  }      
} //showPosition

回答by Talha

use HTML5 GeoLocation:

使用HTML5 地理位置:

function GetGeolocation() {

navigator.geolocation.getCurrentPosition(GetCoords, GetError);

}


function GetCoords(position){

  alert(position.coords.latitude);

  alert(position.coords.longitude);

  alert(position.coords.accuracy);

 var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({'latLng': latlng}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    if (results[1]) {
      map.setZoom(11);
      marker = new google.maps.Marker({
          position: latlng,
          map: map
      });
      infowindow.setContent(results[1].formatted_address);
      infowindow.open(map, marker);
    }
  } else {
    alert("Geocoder failed due to: " + status);
  }
});

}