I'm using Mapquest in an attempt to get latitude and longitude values of a requested address.
This is my call to their API:
$json = file_get_contents('http://www.mapquestapi.com/geocoding/v1/address?key=******&callback=renderOptions&outFormat=json&inFormat=json&json={location:{street:"Lancaster,PA"},options:{thumbMaps:false}}');
$output = json_decode($json, true);
$lat = $output['results'][0]['locations'][0]['latLng']['lat'];
$lng = $output['results'][0]['locations'][0]['latLng']['lng'];
echo $lat.",".$lng;
As you can see, I'm trying to echo the LAT and LNG to screen but it's empty. When I print_r($json), I get the following:
renderOptions({"results":[{"locations":[{"latLng":{"lng":-76.30127,"lat":40.03804},"adminArea4":"Lancaster
County","adminArea5Type":"City"...............
So I know the response is OK and that LAT and LNG are available, but if I print_r($output) I get nothing and if I var_dump($output) I get NULL, and obviously I don't get my LAT LNG data.
I'm not great with JSON and arrays. Can somebody see what I'm doing wrong?
You need to remove &callback=renderOptions from the URL. Right now, the server returns JSONP (with the specified callback function). This is no valid JSON and so json_decode returns NULL (as specified in the manual)
Related
I have a code for downloading longitude and latitude coordinates from google maps, it was working before but now it's returning null value. Below is my code;
<?php
//Optaining Latitude and Longitude
$address = $title;
$url = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&sensor=false");
$response = json_decode($url);
$latitudee = "";
$longitudee = "";
if ($response->status == 'OK') {
$latitudee = $response->results[0]->geometry->location->lat;
$longitudee = $response->results[0]->geometry->location->lng;
}
echo $latitudee;
?>
Google now requires you to include API key for calling geocode API. Change the 'url' variable as follows-
$url = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&key=YOUR_API_KEY");
The sensor parameter is no longer required to pass as per google developer guide
https://developers.google.com/maps/documentation/geocoding/intro
If you don't have an API key, you can get it here-
https://developers.google.com/maps/documentation/javascript/get-api-key
Also don't forget to restrict your key once you have one.
Returned error message states what is the problem here:
Keyless access to Google Maps Platform is deprecated.
Please use an API key with all your API calls to avoid service interruption.
For further details please refer to http://g.co/dev/maps-no-account
After recent changes to google maps, you will need to create an account to use google maps API, this will generate an API key and you have to append it to URL that you use
"http://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&key=YOUR_API_KEY"
you must Formatted your address:
$formattedAddr = str_replace(' ','+',$address);
Send request and receive json data by address:
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false');
$output = json_decode($geocodeFromAddr);
Get latitude and longitute from json data:
if ($output->status == 'OK') {
$data['latitude'] = $output->results[0]->geometry->location->lat;
$data['longitude'] = $output->results[0]->geometry->location->lng;
}
I was able to find where the problem was, Google changed the API url to the one below;
$url = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($add`enter code here`ress)."&key=YOUR_API_KEY");
I am using Overpass Turbo to show information on a map.
Part of my code (I use PHP) is as follows:
//overpass query
$overpass = 'http://overpass-api.de/api/interpreter?data=[out:json];area(3600046663)->.searchArea;(node["amenity"="drinking_water"](area.searchArea););out;';
// collecting results in JSON format
$html = file_get_contents($overpass);
$jsonout = json_decode($html);
// this line just checks what the query would give as output
var_dump($jsonout);
Query results in JSON format (which is what var_dump shows) look like this:
version: 0.6
generator: "Overpass API"
osm3s:
timestamp_osm_base: "2017-11-03T06:25:02Z"
timestamp_areas_base: "2017-11-03T05:45:02Z"
copyright: "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
elements:
0:
type: "node"
id: 254917402
lat: 46.0672187
lon: 11.1379545
tags:
amenity: "drinking_water"
1:
type: "node"
id: 257481472
lat: 46.0687113
lon: 11.1201097
tags:
amenity: "drinking_water"
and so on.
You can see it yourself, copying/pasting the query URL in your browser: http://overpass-api.de/api/interpreter?data=[out:json];area(3600046663)-%3E.searchArea;(node[%22amenity%22=%22drinking_water%22](area.searchArea););out;
As you can see, each element in the array above has latitude and longitude information. I need those to show markers on a map.
I am not able to isolate the lat and lon information from each element in the array. How can I do that?
Here you go:
<?php
// overpass query
$overpass = 'http://overpass-api.de/api/interpreter?data=[out:json];area(3600046663)->.searchArea;(node["amenity"="drinking_water"](area.searchArea););out;';
// collecting results in JSON format
$html = file_get_contents($overpass);
$result = json_decode($html, true); // "true" to get PHP array instead of an object
// elements key contains the array of all required elements
$data = $result['elements'];
foreach($data as $key => $row) {
// latitude
$lat = $row['lat'];
// longitude
$lng = $row['lon'];
}
?>
Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.
I want to parse this URL with PHP to get the latitude of a specific address (2+bis+avenue+Foch75116+Paris+FR):
I use the google maps web service: http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false
// Get the JSON
$url='http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
var_dump($obj);
It doesn't work. I have this error :
OVER_QUERY_LIMIT
So I searched on the web and I found that there is a limitation using google maps api (Min 1 sec between 2 queries and max 2500 queries per day)
Do you know any way to convert an adress to --> Latitude/Longitude ???
You are accessing results incorrectly.
// Get the JSON
$url='http://maps.googleapis.com/maps/api/geocode/json?address=2+bis+avenue+Foch75116+Paris+FR&sensor=false';
$source = file_get_contents($url);
$obj = json_decode($source);
$LATITUDE = $obj->results[0]->geometry->location->lat;
echo $LATITUDE;
I have tried to use Reverse geocoding Webservice in PHP.Response JSON returns Empty response only.
$json_string2='http://maps.googleapis.com/maps/api/geocode/json?latlng=11.49813514,77.24331624&sensor=false';
$obj2=json_decode($json_string2);
$addr2=$obj2->formatted_address;
echo $addr2; //**line 1**
here line 1 prints empty....What is the problem in the coding....
Your problem is you did not get the file before decode to JSON and you also called with the wrong format.
$json_string2 = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=11.49813514,77.24331624&sensor=false');
$obj2 = json_decode($json_string2);
$addr2 = $obj2->results[0]->formatted_address;
echo $addr2; //**line 1**
you could try to print this object before you call its format.
print_r($obj2);