Reputation: 87
I have a google map link that looks like this:
How can I extract coordinates from it in PHP or Javascript to get an array:
{47.620506, -122.349277}
Upvotes: 1
Views: 7340
Reputation: 75
Try this:
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;
}
In my case, I have to make sure that the link is a google map location URL as it all depends on the character "@" in the url.
Upvotes: 0
Reputation: 1401
If you're not using the api (Which isn't advisable), you could just put the page into a string, and extract the long/lat from within ... It's given multiple times on the page as the parameter ll
... I'm not very good with regex, so I'll give an example using 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];
?>
Upvotes: 1
Reputation: 66
If you use php it is quite easy to query the maps api with just about any address that Google will recognize:
$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);
Hope this helps
Upvotes: 0
Reputation: 1107
This is the code I am using on my web page at the moment. It is fairly easy to do as well.
<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>
Upvotes: 1