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

发布于 2024-11-18 02:08:34 字数 75 浏览 2 评论 0 原文

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

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

Is there a way to get a city name from a latitude and longitude point using the google maps api for javascript?

If so could I please see an example?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

硪扪都還晓 2024-11-25 02:08:34

这是一个完整的示例:

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

Here is a complete sample:

<!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>
旧竹 2024-11-25 02:08:34

在node.js中我们可以使用node-geocodernpm模块 获取地址

从 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' } ]

In node.js we can use node-geocoder npm module to get address from 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);
});

output:

node 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' } ]
孤云独去闲 2024-11-25 02:08:34

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

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY

只需更改 YOUR_API_KEY到您从 Google Geocoding API

P/S:Geocoding API 位于地点下,而不是地图下;)

Here is the latest sample of Google's geocode Web Service

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY

Simply change the YOUR_API_KEY to the API key you get from Google Geocoding API

P/S: Geocoding API is under Places NOT Maps ;)

稀香 2024-11-25 02:08:34

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

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

Following Code Works Fine to Get City Name (Using 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>

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;
            }
        }
    );
}
凉城已无爱 2024-11-25 02:08:34

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

BigDataCloud also has a nice API for this, also for nodejs users.

they have API for client - free. But also for backend, using API_KEY (free according to quota).

Their GitHub page.

the code looks like:

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

async foo() {
    ...
    const location: string = await client.getReverseGeocode({
          latitude:'32.101786566878445', 
          longitude: '34.858965073072056'
    });
}
水波映月 2024-11-25 02:08:34

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

In case if you don't want to use google geocoding API than you can refer to few other Free APIs for the development purpose.
for example i used [mapquest] API in order to get the location name.

you can fetch location name easily by implementing this following function

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

明月松间行 2024-11-25 02:08:34

这是使用 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”中的错误状态代码

Here's a modern solution using a 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();
    });
};

And call it like this:

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

The promise returns the address object in 'then' or the error status code in 'catch'

策马西风 2024-11-25 02:08:34

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

Same as @Sanchit Gupta.

in this part

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

just console the results array

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;
}
吃不饱 2024-11-25 02:08:34

以下代码对我来说效果很好
城市,
状态,
国家,
邮政编码
(使用谷歌地图地理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);
            
            }
        });

Following Code Works Fine For Me to Get
City,
state,
country,
zipcode
(Using Google Map Geo 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);
            
            }
        });
谁与争疯 2024-11-25 02:08:34

有许多可用的

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

还提供其他免费和付费工具

There are many tools available

  1. google maps API as like all had written
  2. use this data
    "https://simplemaps.com/data/world-cities"
    download free version and convert excel to JSON with some online converter like "http://beautifytools.com/excel-to-json-converter.php"
  3. use IP address
    which is not good because using IP address of someone may not good
    users think that you can hack them.

other free and paid tools are available also

聆听风音 2024-11-25 02:08:34

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

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

You can use this library in your API based on Node to do reverse geocoding:

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

仙女 2024-11-25 02:08:34

公共函数 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;
      }
  }

public function 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;
      }
  }
诺曦 2024-11-25 02:08:34

你可以使用纯 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;
    }
}

you can do it with pure php and 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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文