首页 > 解决方案 > 如何在laravel中找到给定城市的给定地址?

问题描述

我在一个表中有两个字段,一个是城市,另一个是地址。我必须找出地址是否在城市内。我怎么能找到这个。

用于获取城市的 lat 和 lng

 $city_lat_lng =json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?address={$ogl_city}&sensor=false"));
 $city_lat = $city_lat_lng->results[0]->geometry->location->lat;
 $city_long = $city_lat_lng->results[0]->geometry->location->lng;

用于获取地址的 lat 和 lng

$address_lat_lng = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?address={$ogl_address}&sensor=false"));
$address_lat = $address_lat_lng->results[0]->geometry->location->lat;
$address_long = $address_lat_lng->results[0]->geometry->location->lng;

在上面的代码中,我们可以找到地址和城市的经纬度。但是对于如何查找特定地址是否位于特定城市内,没有任何正确的想法。城市和地址都在这里动态。我是 Laravel 的新手。也在谷歌上搜索但没有得到任何适当的解决方案。

标签: javascriptphplaravel

解决方案


您可以使用 API 响应中的 address_components 来获取城市:

$response = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?address={$ogl_city}&sensor=false"));
$firstOption = $response[0];

for($i=0;$i<count($firstOption['address_components']);$i++)
{
    if (in_array ("administrative_area_level_1", $firstOption['address_components'][$i]['types']))
    {
        echo "city = ". $firstOption['address_components'][$i]['long_name'].PHP_EOL;
    }
}

administrative_area_level_1是一种行政区域,请在此处查看哪些类型符合您对城市的想法: https ://developers.google.com/places/supported_types


推荐阅读