使用地理位置获取城市名称 [英] Get city name using geolocation

查看:145
本文介绍了使用地理位置获取城市名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法使用html5地理位置获取用户的经度和纬度。

  //检查浏览器是否支持W3C Geolocation API 
if(navigator.geolocation){
navigator。 geolocation.getCurrentPosition(successFunction,errorFunction);
}
//获取经度和纬度;
函数successFunction(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
}

我想显示城市名称,它似乎是获取它的唯一方法是使用反向地理位置api。我阅读谷歌的反向地理定位文档,但我不知道如何获得我的网站上的输出。



我不知道如何去使用这个:http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true以显示城市名称。



什么是标准方法?

解决方案

您可以使用Google API做类似的事情。



请注意,您必须包含Google地图库才能使用此功能。 Google地理编码器会返回许多地址组件,因此您必须进行有根据的猜测,以确定哪个城市拥有该城市。

administrative_area_level_1通常是您要查找的内容,但有时候地方性是您所在的城市。

无论如何 - 您可以找到有关Google响应类型的更多详情此处 here



以下是应该做的诀窍:

 <!DOCTYPE html> 
< html>
< head>
< meta name =viewportcontent =initial-scale = 1.0,user-scalable = no/>
< meta http-equiv =content-typecontent =text / html; charset = UTF-8/>
< title>反向地理编码< / title>

< script type =text / javascriptsrc =http://maps.googleapis.com/maps/api/js?sensor=false>< / script>
< script type =text / javascript>
var geocoder;

if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(successFunction,errorFunction);
}
//获取纬度和经度;
函数successFunction(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat,lng)
}

函数errorFunction(){
alert(Geocoder failed);


函数initialize(){
geocoder = new google.maps.Geocoder();



}

函数codeLatLng(lat,lng){

var latlng = new google.maps.LatLng (lat,lng);
geocoder.geocode({'latLng':latlng},function(results,status){
if(status == google.maps.GeocoderStatus.OK){
console.log(results )
if(results [1]){
//格式化地址
alert(results [0] .formatted_address)
//找到国家名称
for(var (var b = 0; b< results [0] .address_components [i] .types.length; b ++){$ b(i = 0; i< results [0] .address_components.length; i ++)
$ b //可能存在不同类型的城市admin_area_lvl_1通常在寻找sublocality类型的情况下会更合适
if(results [0] .address_components [i] .types [b ] ==administrative_area_level_1){
//这是您要查找的对象
city = results [0] .address_components [i];
break;
}
}
}
//城市数据
alert(city.short_name ++ city.long_name)


} else {
alert(找不到结果);
}
} else {
alert(Geocoder failed due to:+ status);
}
});
}
< / script>
< / head>
< body onload =initialize()>

< / body>
< / html>


I managed to get the user's latitude and longitude using html5 geolocation.

//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get latitude and longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
}

I want to display the city name, it seems the only way to get it is to use a reverse geolocation api. I read google's documentation for reverse geolocation but I don't know how to get the output on my site.

I don't know how to go use this: "http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true" to display the city name on the page.

What is standard way to do it?

解决方案

You would do something like that using Google API.

Please note you must include the google maps library for this to work. Google geocoder returns a lot of address components so you must make an educated guess as to which one will have the city.

"administrative_area_level_1" is usually what you are looking for but sometimes locality is the city you are after.

Anyhow - more details on google response types can be found here and here.

Below is the code that should do the trick:

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         alert(results[0].formatted_address)
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data
        alert(city.short_name + " " + city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 

这篇关于使用地理位置获取城市名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆