在邮编10英里范围内寻找城镇。 Google地图API [英] Finding towns within a 10 mile radius of postcode. Google maps API

查看:93
本文介绍了在邮编10英里范围内寻找城镇。 Google地图API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始着眼于Google Maps API,在我的网站上尝试新功能。

 <?php 

$ postcode = $ _REQUEST [''邮编'];

$ url ='http://maps.googleapis.com/maps/api/geocode/xml?address='.$postcode.'&sensor=false';
$ parsedXML = simplexml_load_file($ url);

if($ parsedXML-> status!=OK){
echo存在问题:。 $ parsedXML->的状态;
}

$ myAddress = array();
foreach($ parsedXML-> result-> address_component as $ component){
if(is_array($ component-> type))$ type =(string)$ component-> type [ 0];
else $ type =(string)$ component-> type;

$ myAddress [$ type] =(string)$ component-> long_name;
}
header('Content-Type:application / json');
echo json_encode($ myAddress);


?>

它简单地使用我定义并搜索Google数据库的邮编,然后返回城镇,县等。

如果可能的话,我想不仅要显示最近的城镇,而且还要显示5-10英里范围内的任何地方。有人能告诉我怎么去做这件事吗?



感谢您的任何帮助

解决方案 更新:我写了一篇关于 http://www.mullie.eu/geographic-searches/



-



使用Google Maps API循环访问所有可用的城镇,以获取其纬度&经度。将这些保存到某个地方(数据库)。 - 请注意,谷歌不会接受大量的电话,因此可以节省您的电话费。

然后,在取得城镇时,您可以使用类似于下面代码的代码抓住一定范围内的城市:

  public static function getNearby($ lat,$ lng,$ type ='cities', $ limit = 50,$ distance = 50,$ unit ='km')
{
//地球半径; @note:地球不是完美的球形,但如果($ unit =='km')$ radius = 6371.009;这被认为是'平均半径'
; //以公里为单位
elseif($ unit =='mi')$ radius = 3958.761; //英里

//纬度边界
$ maxLat =(float)$ lat + rad2deg($ distance / $ radius);
$ minLat =(float)$ lat - rad2deg($ distance / $ radius);
$ b $ //经度边界(经度在纬度增加时变小)
$ maxLng =(float)$ lng + rad2deg($ distance / $ radius / cos(deg2rad((float)$ lat )));
$ minLng =(float)$ lng - rad2deg($ distance / $ radius / cos(deg2rad((float)$ lat)));

//得到按距离排序的结果(大约)
$附近=(array)FrontendDB :: getDB() - > retrieve('SELECT *
FROM table
WHERE lat>?AND lat<?AND lng>?lng<?
ORDER BY ABS(lat - ?)+ ABS(lng - ?)ASC
LIMIT?'' ,
array($ minLat,$ maxLat,$ minLng,$ maxLng,(float)$ lat,(float)$ lng,(int)$ limit));

返回附近的$;
}

关于上述代码的提示:




  • 使用自己的数据库包装器,因此转换为mysql_query,PDO ...

  • 这不是确切的。我们无法在数据库中进行精确的球面计算,所以我们已经采用了上面的&低纬度&经度限制。这基本上意味着一个比你的距离稍远的位置(例如,在最远的东北部,实际半径外面(实际上几乎是一个圆圈),但仍在最大纬度和经度内(因为我们将它与数据库中的方形限制进行比较),这只会对你的半径进行粗略但坚定的100%准确选择。


我会试图说明这一点:

  _________________ 
| / \ |
| Y / \ |
| / \ |
|(X)|
| \ / |
| \ / |
| ______ \ _ / ______ |

上面的圆圈(有点)是您想要查找位置的实际半径,基于位置X.这很难直接从数据库中完成,所以我们实际从数据库中获取的是周围的正方形。正如你所看到的,这可能是位置(l ike Y)落入这些最大&尽管它们实际上并没有满足要求的半径。这些可以稍后通过PHP过滤出来。



为了解决最后一个问题,您可以循环所有结果并计算根位置和关闭位置之间的确切距离找到匹配项,计算它们是否确实在您的半径范围内。为此,您可以使用以下代码:

  public static function getDistance($ lat1,$ lng1,$ lat2,$ lng2, $ unit ='km')
{
//地球半径; @note:地球不是完美的球形,但如果($ unit =='km')$ radius = 6371.009;这被认为是'平均半径'
; //以公里为单位
elseif($ unit =='mi')$ radius = 3958.761; //以英里为单位

//将度数转换为弧度
$ lat1 = deg2rad((float)$ lat1);
$ lng1 = deg2rad((float)$ lng1);
$ lat2 = deg2rad((float)$ lat2);
$ lng2 = deg2rad((float)$ lng2);

//大圆距公式
返回$ radius * acos(sin($ lat1)* sin($ lat2)+ cos($ lat1)* cos($ lat2)* cos( $ lng1 - $ lng2));
}

这将计算位置X和位置Y之间的(准)然后你就可以过滤掉那些接近足以通过粗分数据库的城市,但不能太接近实际的范围。


I've recently started looking at the Google Maps API to try out something new in my websites. I am currently using this code:

<?php

$postcode = $_REQUEST['postcode'];

$url = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.$postcode.'&sensor=false';
$parsedXML = simplexml_load_file($url);

if($parsedXML->status != "OK") {
echo "There has been a problem: " . $parsedXML->status;
}

$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
if(is_array($component->type)) $type = (string)$component->type[0];
else $type = (string)$component->type;

$myAddress[$type] = (string)$component->long_name;
}
header('Content-Type: application/json');
echo json_encode($myAddress);


?>

which simply uses a postcode that I define and searches the Google database and then returns the town, county etc.

If possible, I would like to not only show the nearest town but also any within a 5-10 mile radius. Could someone tell me how I would go about doing this please?

Thanks for any help

解决方案

Update: I wrote up a more detailed blogpost about this specific subject on http://www.mullie.eu/geographic-searches/

--

Loop through all available towns using the Google Maps API to fetch their latitude & longitude. Save these somewhere (database). - Beware, Google will not accept an enormous amount of calls, so throttle your calls.

Then, when fetching a town, you can use code similar to the code below to grab the cities withing a certain range:

public static function getNearby($lat, $lng, $type = 'cities', $limit = 50, $distance = 50, $unit = 'km')
{
    // radius of earth; @note: the earth is not perfectly spherical, but this is considered the 'mean radius'
    if ($unit == 'km') $radius = 6371.009; // in kilometers
    elseif ($unit == 'mi') $radius = 3958.761; // in miles

    // latitude boundaries
    $maxLat = (float) $lat + rad2deg($distance / $radius);
    $minLat = (float) $lat - rad2deg($distance / $radius);

    // longitude boundaries (longitude gets smaller when latitude increases)
    $maxLng = (float) $lng + rad2deg($distance / $radius / cos(deg2rad((float) $lat)));
    $minLng = (float) $lng - rad2deg($distance / $radius / cos(deg2rad((float) $lat)));

    // get results ordered by distance (approx)
    $nearby = (array) FrontendDB::getDB()->retrieve('SELECT *
                                                    FROM table
                                                    WHERE lat > ? AND lat < ? AND lng > ? AND lng < ?
                                                    ORDER BY ABS(lat - ?) + ABS(lng - ?) ASC
                                                    LIMIT ?;',
                                                    array($minLat, $maxLat, $minLng, $maxLng, (float) $lat, (float) $lng, (int) $limit));

    return $nearby;
}

Notes about the above code:

  • Own database wrapper is used, so transform to mysql_query, PDO, ...
  • This will not be exact. We can't do exact spherical calculations in the DB, so we've taken the upper & lower latitude & longitude limits. This basically means that a location which is slightly further than your distance (e.g. in the far north-east, just outside of the actual radius (which actually is pretty much a circle), but still inside the max latitude & longitude (because we compare it to square limits in the database). This will just give a rough but nut 100% accurate selection of cities withing your radius.

I'll try to illustrate this:

_________________
|      / \      |
| Y  /     \    |
|  /         \  |
|(      X      )|
|  \         /  |
|    \     /    |
|______\_/______|

The above circle (somewhat) is the actual radius where you want to find locations within, based upon location X. This is too hard to accomplish straight out of your DB, so what we actually fetch from the DB is the surrounding square. As you can see, it's possible that locations (like Y) fall within these max & min boundaries, though they aren't actually withing the requested radius. These can later be filtered out through PHP though.

To tackle this last issue, you could loop all results and calculate the exact distance between both your root location, and the close matches found, to calculate if they're actually within your radius. For that, you could use this code:

public static function getDistance($lat1, $lng1, $lat2, $lng2, $unit = 'km')
{
    // radius of earth; @note: the earth is not perfectly spherical, but this is considered the 'mean radius'
    if ($unit == 'km') $radius = 6371.009; // in kilometers
    elseif ($unit == 'mi') $radius = 3958.761; // in miles

    // convert degrees to radians
    $lat1 = deg2rad((float) $lat1);
    $lng1 = deg2rad((float) $lng1);
    $lat2 = deg2rad((float) $lat2);
    $lng2 = deg2rad((float) $lng2);

    // great circle distance formula
    return $radius * acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($lng1 - $lng2));
}

This will calculate the (quasi) exact distance between location X and location Y, and then you can filter out exactly those cities that were near enough to pass the rough db-fetch, but not just near enough to actually be within your bounds.

这篇关于在邮编10英里范围内寻找城镇。 Google地图API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆