![](/img/trans.png)
[英]How to extract all lat-long coordinates from DirectionsResult object (Google Maps Javascript directions API)
[英]How to extract coordinates from Google Maps link (PHP or Javascript)
我有一个看起来像这样的谷歌地图链接:
如何在 PHP 或 Javascript 中从中提取坐标以获取数组:
{47.620506, -122.349277}
如果您不使用 api(这是不可取的),您可以将页面放入一个字符串中,然后从内部提取 long/lat ......它在页面上多次作为参数ll
.. . 我不太擅长正则表达式,所以我会举一个使用strstr
的例子
<?php
$url='https://www.google.com/maps/place/Space+Needle/@47.620506,-122.349277,17z/data=!4m6!1m3!3m2!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d!2sSpace+Needle!3m1!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d';
$result=file_get_contents($url);
$ll=explode(',',substr(strstr(strstr($result,'?ll='),'&',true),4));
$long=$ll[0];
$lat=$ll[1];
?>
这是我目前在我的网页上使用的代码。 这也很容易做到。
<div id="map-canvas">
<script>
function initialize() {
var myLatlng;
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//User Location
/* This is the cords */ myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//So if you want them individually just use position.coords.l...
//Please feel free to ask questions
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
如果您使用 php,则可以很容易地使用 Google 能够识别的任何地址来查询 maps api:
$address = 'Space+Needle';
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response);
$ltlg = array($result->results[0]->geometry->location->lat, $result->results[0]->geometry->location->lng);
希望这可以帮助
尝试这个:
public function getCoordinatesAttribute() {
$url = "https://www.google.com/maps/place/Space+Needle/@47.620506,-122.349277,17z/data=!4m6!1m3!3m2!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d!2sSpace+Needle!3m1!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d";
$url_coordinates_position = strpos($url, '@')+1;
$coordinates = [];
if ($url_coordinates_position != false) {
$coordinates_string = substr($url, $url_coordinates_position);
$coordinates_array = explode(',', $coordinates_string);
if (count($coordinates_array) >= 2) {
$longitude = $coordinates_array[0];
$latitude = $coordinates_array[1];
$coordinates = [
"longitude" => $longitude,
"latitude" => $latitude
];
}
return $coordinates;
}
return $coordinates;
}
就我而言,我必须确保该链接是一个谷歌地图位置 URL,因为这完全取决于 URL 中的字符“@”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.