如何从地址解析结果中排除路线?

时间:2019-06-06 19:35:53

标签: wordpress google-maps google-geocoder geocode

我正在尝试获取通过表格提交的英国地址的经纬度。该地址可以是完整地址,也可以是城市,也可以是邮政编码,也可以是邮政编码的第一部分。

大多数地理编码请求似乎都能给我正确的输出,但是如果我尝试搜索M25,则地理编码会给我错误的结果,因为它实际上是在伦敦寻找高速公路,而实际上却是在曼彻斯特内寻找一个区域。

是否可以排除在高速公路内进行搜索?

我的代码:

public function get_geocode($address) {
        $url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.$address.',uk&key='.theme_option('theme_options','theme_options_google_api_key');
            $data = @file_get_contents($url);
        $jsondata = json_decode($data,true);
        if (!$this->get_geocode_check_status($jsondata))   return array();
        $location = array(
            'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"],
            'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"],
        );
        return $location;
    }

从上面的代码生成的经纬度将被添加到sql查询中,以获取存储在我数据库中的最近位置。

1 个答案:

答案 0 :(得分:0)

您仅发送邮政编码前缀M5吗?在这种情况下,查询太含糊,地理编码服务不能很好地处理含糊不清的请求。如果您指定更精确的内容,则可以使用(例如M5 4GP,英国)

https://maps.googleapis.com/maps/api/geocode/json?address=M5%204GP%2C%20UK&key=YOUR_API_KEY

还请注意,我在搜索文字中添加了UK,以使搜索结果偏向UK。

在您的情况下,如果您只有邮政编码前缀M5,我建议使用场所自动完成请求作为解决方法。它将返回一些建议,您可以过滤出类型为“ postal_code_prefix”或“ postal_code”的建议。例如,对于“ M5,英国”的请求

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=M5%2C%20UK&key=YOUR_API_KEY

返回5条建议,其中之一的类型为“ postal_code_prefix”

{
  "description":"Salford M5, UK",
  "id":"6cea0bf4efcd39449020500f97a2352cdfd13457",
  "matched_substrings":[
    {
      "length":2,
      "offset":8
    },
    {
      "length":2,
      "offset":12
    }
  ],
  "place_id":"ChIJEVdF_g2ue0gRXkpo4zmLlQM",
  "reference":"ChIJEVdF_g2ue0gRXkpo4zmLlQM",
  "structured_formatting":{
    "main_text":"M5",
    "main_text_matched_substrings":[
      {
        "length":2,
        "offset":0
      }
    ],
    "secondary_text":"Salford, UK",
    "secondary_text_matched_substrings":[
      {
        "length":2,
        "offset":9
      }
    ]
  },
  "terms":[
    {
      "offset":0,
      "value":"Salford"
    },
    {
      "offset":8,
      "value":"M5"
    },
    {
      "offset":12,
      "value":"UK"
    }
  ],
  "types":[
    "postal_code_prefix","postal_code","geocode"
  ]
},

一旦您过滤了此结果并获得了地点ID ChIJEVdF_g2ue0gRXkpo4zmLlQM,就可以对其进行反向地理编码以获取坐标

https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJEVdF_g2ue0gRXkpo4zmLlQM&key=YOUR_API_KEY

在Geocoder工具中查看此结果:

https://google-developers.appspot.com/maps/documentation/utils/geocoder/#place_id%3DChIJEVdF_g2ue0gRXkpo4zmLlQM

我希望这会有所帮助!

相关问题