markdown 使用Google Maps API按地址查找经度和纬度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 使用Google Maps API按地址查找经度和纬度相关的知识,希望对你有一定的参考价值。

# Finding coordinates by address with the Google Maps API

```php
<?php

// Google maps - Geocoding
function google_maps_search($address, $key = '')
{
    $url = sprintf('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s', urlencode($address), urlencode($key));
    $response = file_get_contents($url);
    $data = json_decode($response, 'true');
    return $data;
}

function map_google_search_result($geo)
{
    if (empty($geo['status']) || $geo['status'] != 'OK' || empty($geo['results'][0])) {
        return null;
    }
    $data = $geo['results'][0];
    $postalcode = '';
    foreach ($data['address_components'] as $comp) {
        if (!empty($comp['types'][0]) && ($comp['types'][0] == 'postal_code')) {
            $postalcode = $comp['long_name'];
            break;
        }
    }
    $location = $data['geometry']['location'];
    $formatAddress = !empty($data['formated_address']) ? $data['formated_address'] : null;
    $placeId = !empty($data['place_id']) ? $data['place_id'] : null;

    $result = [
        'lat' => $location['lat'],
        'lng' => $location['lng'],
        'postal_code' => $postalcode,
        'formated_address' => $formatAddress,
        'place_id' => $placeId,
    ];
    return $result;
}

//
// Usage
//

// Your google API key
// https://developers.google.com/maps/documentation/geocoding/usage-limits?hl=de
// 2,500 free requests per day, calculated as the sum of client-side and server-side queries.
// 50 requests per second, calculated as the sum of client-side and server-side queries.
$googleKey = '';

$zip = '10117';
$street = 'Friedrichstrasse 106';
$city = 'Berlin';
$country = 'DE';
$search = implode(', ', [$street, $zip, $city, $country]);

$geoData = google_maps_search($search, $googleKey);
if (!$geoData) {
    echo "Error: " . $id . "\n";
    exit;
}

$mapData = map_google_search_result($geoData);

echo $mapData['lat']; // 52.5227797
echo "\n";
echo $mapData['lng']; // 13.3880986
```

以上是关于markdown 使用Google Maps API按地址查找经度和纬度的主要内容,如果未能解决你的问题,请参考以下文章

Android- Google Maps V2:跟踪从当前位置到另一个目的地的路线

v3 Google Maps Geocoding API 是不是有代表准确性的字段?

如何使用 react-google-maps 显示多个标记

在 maps.google.com 上的缩放比在 Google Maps API v3 上更流畅

google.maps.places.Autocomplete 语言输出

Angular Google Maps - 在 AGM-MAP 标签和使用 map = new google.maps.Map() 之间创建地图差异