Reputation: 2183
I need to retrieve the: street address, nation and maybe also region starting from an array of coordinates.
I'm using this function:
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=false";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
curl_close($curl);
$data = json_decode($curlData);
$address = $data->results[0]->address_components[1]->long_name.', '.$data->results[0]->address_components[0]->long_name;
$country = $data->results[0]->address_components[5]->long_name;
$nation = $data->results[0]->address_components[6]->long_name;
This script itself is working and I get back results, but I've noticed that values are not in the same place every time, (I think depending by the available result) so I got wrong values. Ho can I fix that?
Here are two examples of my output, for one location:
http://urbanfiles.linkmesrl.com/files/uploads/test_address_1.php
http://urbanfiles.linkmesrl.com/files/uploads/test_address_2.php
Any suggestion to get the right value for my results?
Upvotes: 2
Views: 2166
Reputation: 2314
You can loop through the address components and decide the type from the array "types" field.
<?php
foreach($data->results[0]->address_components as $address_component){
if(in_array('country', $address_component->types)){
$country = $address_component->long_name;
continue;
} elseif(in_array('route', $address_component->types)) {
$address = $address_component->long_name;
continue;
}
// etc...
}
Upvotes: 2