栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用地理位置获取城市名称

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用地理位置获取城市名称

您将使用Google API执行类似的操作。

请注意,您必须包括google maps库才能起作用。Google地理编码器会返回很多地址组成部分,因此您必须做出有根据的猜测,以判断哪个人拥有城市。

“ administrative_area_level_1” 通常是您要寻找的,但有时所在地是您追求的城市。

下面是应该完成此技巧的代码:

<!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 geoprer;  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;    preLatLng(lat, lng)}function errorFunction(){    alert("Geoprer failed");}  function initialize() {    geoprer = new google.maps.Geoprer();  }  function preLatLng(lat, lng) {    var latlng = new google.maps.LatLng(lat, lng);    geoprer.geopre({'latLng': latlng}, function(results, status) {      if (status == google.maps.GeoprerStatus.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("Geoprer failed due to: " + status);      }    });  }</script> </head> <body onload="initialize()"></body> </html>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号