如何从经纬度点获取城市名称

How can I get city name from a latitude and longitude point?

本文关键字:城市 获取 经纬度      更新时间:2023-09-26

有没有一种方法可以使用javascript的谷歌地图api从纬度和经度点获取城市名称?

如果是的话,我可以看看一个例子吗?

这被称为反向地理编码

  • 谷歌文档:

    http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding.

  • 谷歌地理编码Web服务示例调用:

    http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.96452&传感器=真&key=YOUR_key

这是一个完整的示例:

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

在node.js中,我们可以使用节点地理编码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' } ]

以下是Google地理编码Web服务的最新示例

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.96452&密钥=YOUR_API_key

只需将YOUR_API_KEY更改为从Google Geocoding API 获得的API密钥

p/S:地理编码API位于地点地图下;(

以下代码可以很好地获取城市名称(使用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;
            }
        }
    );
}

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'
    });
}

如果您不想使用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),
        );
      });
  };

下面是一个使用promise的现代解决方案:

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'中的错误状态代码

与@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;
}

以下代码对我来说很好城市状态国邮政编码(使用谷歌地图地理API(:

 var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key=KEY_HERE&sensor=false";
        $.get(url, function(data) {
        var results = data.results;
            if (data.status === 'OK') 
            {
                //console.log(JSON.stringify(results));
                if (results[0]) 
                {
                    var city = "";
                    var state = "";
                    var country = "";
                    var zipcode = "";
                    
                   var address_components = results[0].address_components;
                    
                    for (var i = 0; i < address_components.length; i++) 
                    {
                       if (address_components[i].types[0] === "administrative_area_level_1" && address_components[i].types[1] === "political") {
                            state = address_components[i].long_name;    
                        }
                        if (address_components[i].types[0] === "locality" && address_components[i].types[1] === "political" ) {                                
                            city = address_components[i].long_name;   
                        }
                        
                        if (address_components[i].types[0] === "postal_code" && zipcode == "") {
                            zipcode = address_components[i].long_name;
                        }
                        
                        if (address_components[i].types[0] === "country") {
                            country = address_components[i].long_name;
                        }
                    }
                  var address = {
                        "city": city,
                        "state": state,
                        "country": country,
                        "zipcode": zipcode,
                  };
                  console.log(address);
               } 
               else 
               {
                   window.alert('No results found');
               }
            } 
            else 
            {
                window.alert('Geocoder failed due to: ' + status);
            
            }
        });

有很多可用的工具

  1. 谷歌地图API就像所有人写的一样
  2. 使用此数据"https://simplemaps.com/data/world-cities"下载免费版本,并使用一些在线转换器将excel转换为JSON,如"http://beautifytools.com/excel-to-json-converter.php">
  3. 使用IP地址这不好,因为使用某人的IP地址可能不好用户认为你可以破解他们

其他免费和付费工具也可用

公共函数retornaCidade($lat,$lng(

  {
      $key      = "SUA CHAVE";
      $url      = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&key=' . $key;
      $geoFull = json_decode ( file_get_contents ( $url ), true );
      if ( $geoFull[ 'results' ] )
      {
          //console.log(JSON.stringify(results));
          if ( $geoFull[ 'results' ][ 0 ] )
          {
              $cidade = "";
              $estado = "";
              $pais   = "";
              $cep    = "";
              $address_components = $geoFull[ 'results' ][ 0 ][ 'address_components' ];
              for ( $i = 0; $i < count ( $address_components ); $i++ )
              {
                  if ( ($address_components[ $i ][ 'types' ][ 0 ] == "administrative_area_level_1") && ($address_components[ $i ][ 'types' ][ 1 ] == "political" ))
                  {
                      $estado = str_replace('State of ', '',$address_components[ $i ][ 'long_name' ]);];
                  }
                  if ( ($address_components[ $i ][ 'types' ][ 0 ] == "administrative_area_level_2") && ($address_components[ $i ][ 'types' ][ 1 ] == "political" ))
                  {
                      $cidade = $address_components[ $i ][ 'long_name' ];
                  }
                  if ( $address_components[ $i ][ 'types' ][ 0 ] == "postal_code" && $cep == "" )
                  {
                      $cep = $address_components[ $i ][ 'long_name' ];
                  }
                  if ($address_components[ $i ][ 'types' ][ 0 ] == "country" )
                  {
                      $pais = $address_components[ $i ][ 'long_name' ];
                  }
              }
              $endereco = [
                  "cidade" => $cidade,
                  "estado" => $estado,
                  "pais"   => $pais,
                  "cep"    => $cep,
              ];
            
              return $endereco;
          }
          else
          {
              return false;
          }
      }
      else
      {
          return false;
      }
  }

您可以在基于Node的API中使用此库来进行反向地理编码:

https://github.com/rapomon/geojson-places

您可以使用纯php和谷歌地理编码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;
    }
}