如何从经纬度获得城市名称?


Answers:


118

太棒了!我仔细阅读了这篇文章,现在已经有太多查询了;)谢谢。
丹尼斯·马丁内斯

如果您使用的是JavaScript API,则每个IP地址和一个用户的身份是相同的,但例如,如果您使用的是PHP,并且您认为将达到这些限制,则需要将请求限制为每秒1次或代理服务器,但请谨慎使用代理,谷歌并不愚蠢,您也无法对其进行抨击。这里更多的信息:developers.google.com/maps/documentation/business/articles/...
安迪·吉

26

这是一个完整的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation API with Google Maps API</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <script>
      function displayLocation(latitude,longitude){
        var request = new XMLHttpRequest();

        var method = 'GET';
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
        var async = true;

        request.open(method, url, async);
        request.onreadystatechange = function(){
          if(request.readyState == 4 && request.status == 200){
            var data = JSON.parse(request.responseText);
            var address = data.results[0];
            document.write(address.formatted_address);
          }
        };
        request.send();
      };

      var successCallback = function(position){
        var x = position.coords.latitude;
        var y = position.coords.longitude;
        displayLocation(x,y);
      };

      var errorCallback = function(error){
        var errorMessage = 'Unknown error';
        switch(error.code) {
          case 1:
            errorMessage = 'Permission denied';
            break;
          case 2:
            errorMessage = 'Position unavailable';
            break;
          case 3:
            errorMessage = 'Timeout';
            break;
        }
        document.write(errorMessage);
      };

      var options = {
        enableHighAccuracy: true,
        timeout: 1000,
        maximumAge: 0
      };

      navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options);
    </script>
  </body>
</html>

没有用户的认可,有没有办法从纬度和经度中找出用户的位置?
维卡斯·维尔玛

8
@VikasVerma,如果允许您在未经用户同意的情况下查找用户位置,将是严重的隐私
侵害

@omerio谢谢,但是我在那儿做了代码,如果他/她想继续,我强迫用户单击允许。
Vikas Verma 2014年

1
实际上,这给了我确切的家庭住址。正是我想要的。如何提取城市和州或邮递区号?
ydobonebi 2015年

6

在node.js中,我们可以使用node-geocoder npm模块从lat,lng。获取地址,

geo.js

var NodeGeocoder = require('node-geocoder');

var options = {
  provider: 'google',
  httpAdapter: 'https', // Default
  apiKey: ' ', // for Mapquest, OpenCage, Google Premier
  formatter: 'json' // 'gpx', 'string', ...
};

var geocoder = NodeGeocoder(options);

geocoder.reverse({lat:28.5967439, lon:77.3285038}, function(err, res) {
  console.log(res);
});

输出:

节点geo.js

[ { formattedAddress: 'C-85B, C Block, Sector 8, Noida, Uttar Pradesh 201301, India',
    latitude: 28.5967439,
    longitude: 77.3285038,
    extra: 
     { googlePlaceId: 'ChIJkTdx9vzkDDkRx6LVvtz1Rhk',
       confidence: 1,
       premise: 'C-85B',
       subpremise: null,
       neighborhood: 'C Block',
       establishment: null },
    administrativeLevels: 
     { level2long: 'Gautam Buddh Nagar',
       level2short: 'Gautam Buddh Nagar',
       level1long: 'Uttar Pradesh',
       level1short: 'UP' },
    city: 'Noida',
    country: 'India',
    countryCode: 'IN',
    zipcode: '201301',
    provider: 'google' } ]

感谢您提供的非常清晰和有效的反馈,'node-geocoder'和'@ google / maps'的选择之间是否会有区别吗?尽管如此,它们似乎做同样的事情
Ade

1
两者的输出是相同的,但是node-geocoder是简化的获取地址的模块,而@ google / maps是获取地址的api,我们需要对其进行配置。
KARTHIKEYAN.A

5

这是使用诺言的现代解决方案:

function getAddress (latitude, longitude) {
    return new Promise(function (resolve, reject) {
        var request = new XMLHttpRequest();

        var method = 'GET';
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true';
        var async = true;

        request.open(method, url, async);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    var data = JSON.parse(request.responseText);
                    var address = data.results[0];
                    resolve(address);
                }
                else {
                    reject(request.status);
                }
            }
        };
        request.send();
    });
};

并这样称呼它:

getAddress(lat, lon).then(console.log).catch(console.error);

Promise在“ then”中返回地址对象,在“ catch”中返回错误状态代码


2
没有访问密钥将无法使用。传感器参数也过时了
Joro Tenev '18


3

以下代码可以很好地获取城市名称(使用Google Map Geo API):

的HTML

<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>

脚本

var x=document.getElementById("demo");
function getLocation(){
    if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else{
        x.innerHTML="Geolocation is not supported by this browser.";
    }
}

function showPosition(position){
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    displayLocation(lat,lon);
}

function showError(error){
    switch(error.code){
        case error.PERMISSION_DENIED:
            x.innerHTML="User denied the request for Geolocation."
        break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
        break;
        case error.TIMEOUT:
            x.innerHTML="The request to get user location timed out."
        break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="An unknown error occurred."
        break;
    }
}

function displayLocation(latitude,longitude){
    var geocoder;
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude);

    geocoder.geocode(
        {'latLng': latlng}, 
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    x.innerHTML = "city name is: " + city;
                }
                else  {
                    x.innerHTML = "address not found";
                }
            }
            else {
                x.innerHTML = "Geocoder failed due to: " + status;
            }
        }
    );
}

0

与@Sanchit Gupta相同。

在这部分

if (results[0]) {
 var add= results[0].formatted_address ;
 var  value=add.split(",");
 count=value.length;
 country=value[count-1];
 state=value[count-2];
 city=value[count-3];
 x.innerHTML = "city name is: " + city;
}

只是控制台结果数组

if (results[0]) {
 console.log(results[0]);
 // choose from console whatever you need.
 var city = results[0].address_components[3].short_name;
 x.innerHTML = "city name is: " + city;
}


-1

BigDataCloud对此也有一个不错的API,也适用于nodejs用户。

他们有免费的客户端API。而且对于后端,使用API​​_KEY(根据配额免费)。

他们的GitHub页面

代码如下:

const client = require('@bigdatacloudapi/client')(API_KEY);

async foo() {
    ...
    const location: string = await client.getReverseGeocode({
          latitude:'32.101786566878445', 
          longitude: '34.858965073072056'
    });
}

-1

如果您不想使用Google地理编码API,则可以参考其他一些免费API进行开发。例如,我使用[mapquest] API来获取位置名称。

您可以通过实现以下功能轻松获取位置名称

 const fetchLocationName = async (lat,lng) => {
    await fetch(
      'https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location='+lat+'%2C'+lng+'&outFormat=json&thumbMaps=false',
    )
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(
          'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson),
        );
      });
  };


OP要求使用Google Maps API解决方案,我想您没有回答这个问题。
米哈尔Tkaczyk

抱歉,但我只是建议了另一种方法。如果他有Google地理编码api密钥,它确实可以正常工作。
pankaj chaturvedi

-3

您可以使用纯PHP和Google Geocode API来做到这一点

/*
 *
 * @param latlong (String) is Latitude and Longitude with , as separator for example "21.3724002,39.8016229"
 **/
function getCityNameByLatitudeLongitude($latlong)
{
    $APIKEY = "AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Replace this with your google maps api key 
    $googleMapsUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latlong . "&language=ar&key=" . $APIKEY;
    $response = file_get_contents($googleMapsUrl);
    $response = json_decode($response, true);
    $results = $response["results"];
    $addressComponents = $results[0]["address_components"];
    $cityName = "";
    foreach ($addressComponents as $component) {
        // echo $component;
        $types = $component["types"];
        if (in_array("locality", $types) && in_array("political", $types)) {
            $cityName = $component["long_name"];
        }
    }
    if ($cityName == "") {
        echo "Failed to get CityName";
    } else {
        echo $cityName;
    }
}

1
不是JavaScript解决方案
Chintan Pathak
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.