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

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

//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; } 

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

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

什么是标准的做法呢?

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

请注意,您必须包括谷歌地图库才能正常工作。 Google地理编码器会返回大量的地址组件,因此您必须进行有根据的猜测,以确定哪个城市拥有该城市。

“administrative_area_level_1”通常是你正在寻找的东西,但有时候地方性是你所追求的城市。

无论如何 – 关于谷歌响应types的更多细节可以在这里和这里find。

下面是应该做的诀窍代码:

 <!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> 

另一种方法是使用我的服务http://ipinfo.io ,根据用户的当前IP地址返回城市,地区和国家的名称。 这是一个简单的例子:

 $.get("http://ipinfo.io", function(response) { console.log(response.city, response.country); }, "jsonp"); 

下面是一个更详细的JSFiddle示例,它也打印出完整的响应信息,所以您可以看到所有可用的详细信息: http : //jsfiddle.net/zK5FN/2/

使用html5地理定位需要用户权限。 如果你不想这样做,去像https://geoip-db.com这样的外部定位器支持IPv6。;

  • JSON: https : //geoip-db.com/json
  • JSONP: https : //geoip-db.com/jsonp

例:

 <!DOCTYPE html> <html> <head> <title>GEOIP DB - jQuery example</title> <script src="jquery-3.1.1.min.js"></script> </head> <body> <div>Country: <span id="country"></span> <div>State: <span id="state"></span> <div>City: <span id="city"></span> <div>Latitude: <span id="latitude"></span> <div>Longitude: <span id="longitude"></span> <div>IP: <span id="ip"></span> <script> $.ajax({ url: "https://geoip-db.com/jsonp", jsonpCallback: "callback", dataType: "jsonp", success: function( location ) { $('#country').html(location.country_name); $('#state').html(location.state); $('#city').html(location.city); $('#latitude').html(location.latitude); $('#longitude').html(location.longitude); $('#ip').html(location.IPv4); } }); </script> </body> </html> 

对于一个纯粹的JavaScript例子,不使用jQuery,看看这个答案。

这里是更新的工作版本,我会得到城市/镇,它看起来像一些字段被修改的JSON响应。 提到以前的答案这个问题。 (感谢米哈尔和一个更多的参考: 链接

 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) { if (results[1]) { var arrAddress = results; console.log(results); $.each(arrAddress, function(i, address_component) { if (address_component.types[0] == "locality") { console.log("City: " + address_component.address_components[0].long_name); itemLocality = address_component.address_components[0].long_name; } }); } else { alert("No results found"); } } else { alert("Geocoder failed due to: " + status); } }); } 

您可以使用Google地图地理编码API获取城市,国家,街道名称和其他地理数据的名称

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script> </head> <body> <script type="text/javascript"> navigator.geolocation.getCurrentPosition(success, error); function success(position) { console.log(position.coords.latitude) console.log(position.coords.longitude) var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en'; $.getJSON(GEOCODING).done(function(location) { console.log(location) }) } function error(err) { console.log(err) } </script> </body> </html> 

并使用jQuery在页面上显示这些数据

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script> </head> <body> <p>Country: <span id="country"></span></p> <p>State: <span id="state"></span></p> <p>City: <span id="city"></span></p> <p>Address: <span id="address"></span></p> <p>Latitude: <span id="latitude"></span></p> <p>Longitude: <span id="longitude"></span></p> <script type="text/javascript"> navigator.geolocation.getCurrentPosition(success, error); function success(position) { var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en'; $.getJSON(GEOCODING).done(function(location) { $('#country').html(location.results[0].address_components[5].long_name); $('#state').html(location.results[0].address_components[4].long_name); $('#city').html(location.results[0].address_components[2].long_name); $('#address').html(location.results[0].formatted_address); $('#latitude').html(position.coords.latitude); $('#longitude').html(position.coords.longitude); }) } function error(err) { console.log(err) } </script> </body> </html> 

geolocator.js可以做到这一点。 (我是作者)。

获取城市名称(有限地址)

 geolocator.locateByIP(options, function (err, location) { console.log(location.address.city); }); 

获取完整的地址信息

下面的示例将首先尝试使用HTML5 Geolocation API来获取确切的坐标。 如果失败或被拒绝,它将回退到Geo-IP查找。 一旦获得坐标,它将反向地理编码坐标到一个地址。

 var options = { enableHighAccuracy: true, fallbackToIP: true, // fallback to IP if Geolocation fails or rejected addressLookup: true }; geolocator.locate(options, function (err, location) { console.log(location.address.city); }); 

这在内部使用Google API(用于地址查询)。 所以在这个调用之前,您应该使用您的Google API密钥configurationgeolocator。

 geolocator.config({ language: "en", google: { version: "3", key: "YOUR-GOOGLE-API-KEY" } }); 

Geolocator支持地理位置(通过HTML5或IP查找),地理编码,地址查找(反向地理编码),距离和持续时间,时区信息和更多的function…

经过一些search和我自己的东西拼凑了几个不同的解决scheme后,我想出了这个function:

 function parse_place(place) { var location = []; for (var ac = 0; ac < place.address_components.length; ac++) { var component = place.address_components[ac]; switch(component.types[0]) { case 'locality': location['city'] = component.long_name; break; case 'administrative_area_level_1': location['state'] = component.long_name; break; case 'country': location['country'] = component.long_name; break; } }; return location; } 

您可以使用https://ip-api.io/获取城市名称。; 它支持IPv6。

作为奖励,它允许检查IP地址是否是tor节点,公共代理或垃圾邮件发送者。

Javascript代码:

 $(document).ready(function () { $('#btnGetIpDetail').click(function () { if ($('#txtIP').val() == '') { alert('IP address is reqired'); return false; } $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(), function (result) { alert('City Name: ' + result.city) console.log(result); }); }); }); 

HTML代码

 <script src="jquery-1.12.4.js"></script> <div> <input type="text" id="txtIP" /> <button id="btnGetIpDetail">Get Location of IP</button> </div> 

JSON输出

 { "ip": "64.30.228.118", "country_code": "US", "country_name": "United States", "region_code": "FL", "region_name": "Florida", "city": "Fort Lauderdale", "zip_code": "33309", "time_zone": "America/New_York", "latitude": 26.1882, "longitude": -80.1711, "metro_code": 528, "suspicious_factors": { "is_proxy": false, "is_tor_node": false, "is_spam": false, "is_suspicious": false } } 

这里是另一个去吧..添加更多的接受的答案可能更全面..当然switch-case将使它看起来优雅。

 function parseGeoLocationResults(result) { const parsedResult = {} const {address_components} = result; for (var i = 0; i < address_components.length; i++) { for (var b = 0; b < address_components[i].types.length; b++) { if (address_components[i].types[b] == "street_number") { //this is the object you are looking for parsedResult.street_number = address_components[i].long_name; break; } else if (address_components[i].types[b] == "route") { //this is the object you are looking for parsedResult.street_name = address_components[i].long_name; break; } else if (address_components[i].types[b] == "sublocality_level_1") { //this is the object you are looking for parsedResult.sublocality_level_1 = address_components[i].long_name; break; } else if (address_components[i].types[b] == "sublocality_level_2") { //this is the object you are looking for parsedResult.sublocality_level_2 = address_components[i].long_name; break; } else if (address_components[i].types[b] == "sublocality_level_3") { //this is the object you are looking for parsedResult.sublocality_level_3 = address_components[i].long_name; break; } else if (address_components[i].types[b] == "neighborhood") { //this is the object you are looking for parsedResult.neighborhood = address_components[i].long_name; break; } else if (address_components[i].types[b] == "locality") { //this is the object you are looking for parsedResult.city = address_components[i].long_name; break; } else if (address_components[i].types[b] == "administrative_area_level_1") { //this is the object you are looking for parsedResult.state = address_components[i].long_name; break; } else if (address_components[i].types[b] == "postal_code") { //this is the object you are looking for parsedResult.zip = address_components[i].long_name; break; } else if (address_components[i].types[b] == "country") { //this is the object you are looking for parsedResult.country = address_components[i].long_name; break; } } } return parsedResult; } 

正如@PirateApp在他的评论中提到的那样,它明确反对Google Maps API Licensing以按照您的意图使用Maps API。

您有许多select,包括下载Geoip数据库并在本地查询或使用第三方API服务,例如mine ipdata.co

 $.get("https://api.ipdata.co", function(response) { $("#ip").html("IP: " + response.ip); $("#city").html(response.city + ", " + response.region); $("#response").html(JSON.stringify(response, null, 4)); }, "jsonp"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1> <div id="ip"></div> <div id="city"></div> <pre id="response"></pre>