如何获取经纬度通过代码

How to acquire Longitude and Latitude via Code

本文关键字:经纬度 代码 获取 何获取      更新时间:2023-09-26

我被要求定位一个特定地点的经度和纬度。用户将给出该地点的地址。我怎样才能得到经度和纬度?

您需要执行所谓的地理编码,以便将地址文本转换为一对经纬度坐标。一般来说,这方面的好服务有某种配额或付费订阅模式,但你可以在以下网址找到一些免费的API:

http://www.programmableweb.com/news/7-free-geocoding-apis-google-bing-yahoo-and-mapquest/2012/06/21

进一步的谷歌工作将找到其他提供商,因为我已经提供了关键术语:地理编码。许多有Javascript, PHP, c#和其他实现示例来帮助您开始。

我使用google api从我的项目地址获取地理坐标:

class Google
{
    private function __construct() { }
    public static function getGoogleJson($address)
    {
        $apiLink = 'http://maps.google.com/maps/api/geocode/json?sensor=false&language=ru&address=' . urlencode($address);
        $tmp = @json_decode(file_get_contents($apiLink));
        if (!$tmp) {
            return new stdClass;
        } else {
            return $tmp;
        }
    }
    public static function getGeoByAddress($address)
    {
        $addr = self::getGoogleJson($address);
        if (isset($addr->results[0]->geometry->location)) {
            return (array)$addr->results[0]->geometry->location;
        } else {
            return ['lat' => 0, 'lng' => 0];
        }
    }
}

(立正!Google对每天使用这个api有一些限制)