JSON array - extract the lat lng - php

I have a function that is trying to get the coordinates from a json array. It has me stumped so I was hoping someone would see my error.
function getCoords($location){
$loc = urlencode($location);
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$loc&sensor=false";
//echo $url;
//echo file_get_contents($geo_url);
$json_result = json_decode(file_get_contents($url));
$geo_result = $json_result->results[0];
$aCsv = $geo_result->geometry->location;
//see if the it is locating the real address or just apox location, or in most cases a bad address
if($aCsv->location[0] == 200) {
return array('lat'=>(float)$aCsv[2], 'lng'=>(float)$aCsv[3], 'prec'=>(int)$aCsv[1]);
}
var_dump($aCsv);
}
The var dump is below I need to extract just the lat and lng in this format 42.3584308,-71.0597732, 21.3069444, -157.8583333
object(stdClass)#12 (2) { ["lat"]=> float(42.3584308) ["lng"]=> float(-71.0597732) } object(stdClass)#6 (2) { ["lat"]=> float(21.3069444) ["lng"]=> float(-157.8583333) }
I think this part is where I am running into my issue
if($aCsv->location[0] == 200) {
return array('lat'=>(float)$aCsv[2], 'lng'=>(float)$aCsv[3], 'prec'=>(int)$aCsv[1]);
TIA steve
Guys is there a way to access the JSON data outside of the function? I would like to take the actual address that is being parsed and show that in the result ing calculation.
Sometimes google maps does not use the exact location for instance if I type in KLAX - Los Angeles airport if uses a address in Germany but if I put LAX it uses teh LA airport so it would be nice to see the parsed address as well.
I can echo the address thats being parsed within the function but when I try to use it outside the function it is NULL.
Thanks Again for your assistance.
Steve

Trees and woods? You already have it !!
function getCoords($location){
$loc = urlencode($location);
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$loc&sensor=false";
$json_result = json_decode(file_get_contents($url));
$geo_result = $json_result->results[0];
$aCsv = $geo_result->geometry->location;
echo 'lat : '.$aCsv->lat.'<br>';
echo 'lng : '.$aCsv->lng.'<br>';
}
getCoords('alabama');
outputs
lat : 32.3182314
lng : -86.902298

try this
$data = json_decode($ResponseData);
if('OK' === $data->status){
$latitude = $data->results['0']->geometry->location->lat;
$longitude = $data->results['0']->geometry->location->lng;
}

It's easier to work with a assoziative array so you can use this:
$json_result = json_decode(file_get_contents($url),true)
(http://php.net/manual/de/function.json-decode.php)
Then the values are available with:
$json_result["lng"]
etc.

Use this
$geocode = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$loc.'&sensor=true');
$output = json_decode($geocode);
if($output->results)
{
foreach($output as $data)
{
$lat = $data[0]->geometry->location->lat;
$long = $data[0]->geometry->location->lng;
$location = $data[0]->formatted_address;
}
}

Related

i want to find my lat long in a particular area coordinates arrays in php

I want to find my lat-long exist or not in a particular area in PHP
Area coordinates JSON array ->
{"lat":[21.39664174642479,21.39664174642479,21.39664174642479,21.39664174642479,21.38641226905212,21.38129726211495,21.376182076389874,21.371066711911467,21.365951168714215,21.36083544683268,21.355719546301387,21.350603467154897,21.34037077315456,21.33525415836984,21.33013736510819,21.31478591480751,21.30966840798403,21.304550722856618,21.29943285945987,21.289196597996938,21.2840782,21.27895962387228,21.27384086964844,21.268721937363132,21.263602827051027,21.268721937363132,21.268721937363132,21.27384086964844,21.27895962387228,21.2840782,21.289196597996938,21.294314817828436,21.30966840798403,21.31990324329242,21.33013736510819,21.33525415836984,21.34037077315456,21.345487209427773,21.350603467154897,21.355719546301387,21.36083544683268,21.371066711911467,21.376182076389874,21.38641226905212,21.39152709716691,21.39664174642479,21.401756216791277,21.406870508231872,21.41198462071206,21.41198462071206,21.406870508231872,21.401756216791277],"lng":[40.44953843828125,40.45503160234375,40.46601793046875,40.47151109453125,40.48799058671875,40.49348375078125,40.49897691484375,40.50447007890625,40.50447007890625,40.50996324296875,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.50996324296875,40.50447007890625,40.49897691484375,40.48249742265625,40.47700425859375,40.46601793046875,40.46052476640625,40.45503160234375,40.44953843828125,40.43855211015625,40.42756578203125,40.41657945390625,40.40559312578125,40.40559312578125,40.40559312578125,40.40559312578125,40.41108628984375,40.42207261796875,40.42207261796875,40.42756578203125,40.42756578203125,40.43305894609375,40.43305894609375,40.43305894609375,40.43305894609375,40.44404527421875,40.44953843828125,40.45503160234375,40.46601793046875,40.47700425859375]}
You can use the json_decode in php for this. You can find more on the function Here
<?php
$latsToCheck = array(
// ENTER LATITUDES HERE THAT YOU NEED TO CHECK
);
$langsToCheck = array(
// ENTER LONGITUDES HERE THAT YOU NEED TO CHECK
);
$str = '{"lat":[21.39664174642479,21.39664174642479,21.39664174642479,21.39664174642479,21.38641226905212,21.38129726211495,21.376182076389874,21.371066711911467,21.365951168714215,21.36083544683268,21.355719546301387,21.350603467154897,21.34037077315456,21.33525415836984,21.33013736510819,21.31478591480751,21.30966840798403,21.304550722856618,21.29943285945987,21.289196597996938,21.2840782,21.27895962387228,21.27384086964844,21.268721937363132,21.263602827051027,21.268721937363132,21.268721937363132,21.27384086964844,21.27895962387228,21.2840782,21.289196597996938,21.294314817828436,21.30966840798403,21.31990324329242,21.33013736510819,21.33525415836984,21.34037077315456,21.345487209427773,21.350603467154897,21.355719546301387,21.36083544683268,21.371066711911467,21.376182076389874,21.38641226905212,21.39152709716691,21.39664174642479,21.401756216791277,21.406870508231872,21.41198462071206,21.41198462071206,21.406870508231872,21.401756216791277],"lng":[40.44953843828125,40.45503160234375,40.46601793046875,40.47151109453125,40.48799058671875,40.49348375078125,40.49897691484375,40.50447007890625,40.50447007890625,40.50996324296875,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.51545640703125,40.50996324296875,40.50447007890625,40.49897691484375,40.48249742265625,40.47700425859375,40.46601793046875,40.46052476640625,40.45503160234375,40.44953843828125,40.43855211015625,40.42756578203125,40.41657945390625,40.40559312578125,40.40559312578125,40.40559312578125,40.40559312578125,40.41108628984375,40.42207261796875,40.42207261796875,40.42756578203125,40.42756578203125,40.43305894609375,40.43305894609375,40.43305894609375,40.43305894609375,40.44404527421875,40.44953843828125,40.45503160234375,40.46601793046875,40.47700425859375]}';
$result = json_decode($str, true);
if (in_array($latsToCheck, $result['lat']) && in_array($langsToCheck, $result['lng'])) {
echo "co-ordinates exist";
} else {
echo "co-ordinates doesn't exist";
}
?>
Hope this helps.
Try below one
$latlngInfo = 'your lat lng json data';
$arrMixLatLang = json_decode($latlngInfo, 1);
// to check its available or not
if(in_array('lat value', $arrMixLatLang['lat']) && in_array('lng value', $arrMixLatLang['lng'])){
//Your statement
}
// to get index
$latindex = array_search('lat value', $arrMixLatLang['lat']);
$lngindex = array_search('lng value', $arrMixLatLang['lng']);

best way to get city name from google reverse geocoding api php

i am trying to get city name from google reverse geocoding api, my code is displaying full address of the location but i need only city. bellow is my code
<?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
//Send request and receive json data by latitude and longitude
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
//Get address from json data
//$location = $data->results[0]->formatted_address;
$location = $data->results[0]->address_components;
}else{
$location = '';
}
//Print city
$_SESSION['getgeoloc']=$location[6]->long_name;
echo $location;
}
?>
i tried below code to display city, but some times its showing zip code and sometimes city name
$_SESSION['getgeoloc']=$location[6]->long_name;
is there any best way ?
Here is the solution,
<?php
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$lng.'&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK") {
//Get address from json data
for ($j=0;$j<count($data->results[0]->address_components);$j++) {
$cn=array($data->results[0]->address_components[$j]->types[0]);
if(in_array("locality", $cn)) {
$city= $data->results[0]->address_components[$j]->long_name;
}
}
} else{
echo 'Location Not Found';
}
//Print city
echo $city;
This has solved my problem and works great. The main part is the for loop,
for ($j=0;$j<count($data->results[0]->address_components);$j++) {
$cn=array($data->results[0]->address_components[$j]->types[0]);
if (in_array("locality", $cn)) {
$city= $data->results[0]->address_components[$j]->long_name;
}
}
Hope this helps.
You can specify a result_type = locality in the query params like shown below.
For more information about filters, you can search for Optional parameters in a reverse Geocoding request documentation.
https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding

Get country name from latitude and longitude

I have a latitude and a longitude, and I need to fetch country.
I am using this:
$geocode_stats = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=".$deal_lat.",".$deal_long . "&sensor=false");
$output_deals = json_decode($geocode_stats);
$country = $output_deals->results[2]->address_components[4]->long_name;
Sometimes it gives a correct country name, but sometimes it gives blank values, and sometimes it returns a city name.
Can anybody help?
I wrote a function to make it easy. Simply pass in your geo-address which can be a full address, zip code, or in your case latitude and longitude. It will then search through the address component array for the country. In the case that it is unable to find the county it will simply return null, you can change that to an empty string ("") if you need to.
function getGeoCounty($geoAddress) {
$url = 'http://maps.google.com/maps/api/geocode/json?address=' . $geoAddress .'&sensor=false';
$get = file_get_contents($url);
$geoData = json_decode($get);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \InvalidArgumentException('Invalid geocoding results');
}
if(isset($geoData->results[0])) {
foreach($geoData->results[0]->address_components as $addressComponent) {
if(in_array('administrative_area_level_2', $addressComponent->types)) {
return $addressComponent->long_name;
}
}
}
return null;
}
Get complete Address from latitude and longitude.
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
$json = #file_get_contents($url);$data=json_decode($json);
echo $data->results[0]->formatted_address;
$deal_lat=30.469301;
$deal_long=70.969324;
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$deal_lat.','.$deal_long.'&sensor=false');
$output= json_decode($geocode);
for($j=0;$j<count($output->results[0]->address_components);$j++){
$cn=array($output->results[0]->address_components[$j]->types[0]);
if(in_array("country", $cn)){
$country= $output->results[0]->address_components[$j]->long_name;
}
}
echo $country;
$deal_lat=30.469301;
$deal_long=70.969324;
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$deal_lat.','.$deal_long.'&sensor=false');
$output= json_decode($geocode);
for($j=0;$j<count($output->results[0]->address_components);$j++){
$cn=array($output->results[0]->address_components[$j]->types[0]);
if(in_array("country", $cn)){
$country= $output->results[0]->address_components[$j]->long_name;
}
}
echo $country;
I did take the code of matwonk as base.
function getGeoCounty($geoAddress) {
$url = 'http://maps.google.com/maps/api/geocode/json?address=' . urlencode($geoAddress) .'&sensor=false';
$get = file_get_contents($url);
$geoData = json_decode($get);
if(isset($geoData->results[0])) {
$return = array();
foreach($geoData->results[0]->address_components as $addressComponet) {
if(in_array('political', $addressComponet->types)) {
if($addressComponet->short_name != $addressComponet->long_name)
$return[] = $addressComponet->short_name. " - " . $addressComponet->long_name;
else
$return[] = $addressComponet->long_name;
}
}
return implode(", ",$return);
}
return null;
}
The code return in format: neighborhood, City, State, Country
if detect a shortname (as country code or state code) appear in format CODE - NAME.
$latlng = '22.7314,75.88243';
$request_url = "http://maps.googleapis.com/maps/api/geocode /xml?latlng=".$latlng."&sensor=true";
$xml = simplexml_load_file($request_url);
if($xml->status == "OK") {
$address = $xml->result->formatted_address;
foreach ($xml->result->address_component as $address) {
if("country" == trim($address->type)) {
$country = $address->short_name;
}
}
}

preg match for xml output node

I have the following script that uses the api on hostip.info. The page parses an xml readout of a user location based on the ip address. In my function everything is working except for the city.
preg_match("#<Hostip>(\s)*<gml:name>(.*?)</gml:name>#si",$xml,$city_match);
I have narrowed it down to my preg_match being wrong but I'm not sure how to fix it. Here is a sample xml output: http://api.hostip.info/?ip=12.215.42.19
<?php
function getCountryCity()
{
if(isset($_SERVER['REMOTE_ADDR']) && strlen($_SERVER['REMOTE_ADDR']) > 0) {
$ipAddr = $_SERVER['REMOTE_ADDR'];
// verify the IP address
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array();
// get the XML result from hostip.info
$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);
// get the city name inside the node <gml:name> and </gml:name>
preg_match("#<Hostip>(\s)*<gml:name>(.*?)</gml:name>#si",$xml,$city_match);
$ipDetail['city'] = $city_match[1];
// get the country name inside the node <countryName> and </countryName>
preg_match("#<countryName>(.*?)</countryName>#si",$xml,$country_match);
$ipDetail['country'] = $country_match[1];
// get the country name inside the node <countryName> and </countryName>
preg_match("#<countryAbbrev>(.*?)</countryAbbrev>#si",$xml,$cc_match);
$ipDetail['country_code'] = $cc_match[1];
// return the array containing city, country and country code
return $ipDetail;
} else {
return false;
}
}
$ipDetail = getCountryCity();
$user_city = $ipDetail['city'];
$user_country = $ipDetail['country'];
$user_cc = $ipDetail['country_code'];
echo $user_country.' ('.$user_cc.')';
echo $user_city;
?>
XPATH is a dream for this kind of stuff. Google "SimpleXML PHP Tutorial" if this is new to you. Basically:
$xml = new SimpleXMLElement($yourXML);
$user_city = $xml->xpath('//gml:name/text()');
$user_country= $xml->xpath('//countryName/text()');
$cc= $xml->xpath('//countryAbbrev/text()');
I find XPATH queries to be much easier to write than RegEx.
Sorry this doesn't answer your question as directly as you want. tried to post in a comment but the formatting gets totally screwed up
preg_match_all("#<gml:name>(.*?)</gml:name>#si",$xml,$city_match);
just remove <Hostip>(\s)* and use preg_match_all it will take all the tags. Then you can select one you need in array.
function getCountryCity() {
if(isset($_SERVER['REMOTE_ADDR']) && strlen($_SERVER['REMOTE_ADDR']) > 0) {
$user_ip = $_SERVER['REMOTE_ADDR'];
$response = file_get_contents('http://api.hostip.info/?ip='.$user_ip);
$user_details = array();
$xml = new DOMDocument();
$xml->loadXml($response);
$xpath = new DOMXpath($xml);
$path = '/HostipLookupResultSet/gml:featureMember/Hostip/';
// create values for array
$ip = $xpath->evaluate($path . 'ip')->item(0)->nodeValue;
$city = $xpath->evaluate($path . 'gml:name')->item(0)->nodeValue;
$countryName = $xpath->evaluate($path . 'countryName')->item(0)->nodeValue;
$countryAbbrev = $xpath->evaluate($path . 'countryAbbrev')->item(0)->nodeValue;
// assign values to array
$user_details['ip'] = $ip;
$user_details['city'] = $city;
$user_details['countryName'] = $countryName;
$user_details['countryAbbrev'] = $countryAbbrev;
return $user_details;
} else {
return false;
}
}

failed to get latitude , longitude using google maps , get_lat_long_from_address

hi i am trying to get latitude and longitude values by address
function get_lat_long_from_address($address)
{
$lat = 0;
$lng = 0;
if ($this->geocodeCaching) { // if caching of geocode requests is activated
$CI =& get_instance();
$CI->load->database();
$CI->db->select("latitude,longitude");
$CI->db->from("geocoding");
$CI->db->where("address", trim(strtolower($address)));
$query = $CI->db->get();
if ($query->num_rows()>0) {
$row = $query->row();
return array($row->latitude, $row->longitude);
}
}
$data_location = "http://maps.google.com/maps/api/geocode/json?address=".str_replace(" ", "+", $address)."&sensor=".$this->sensor;
if ($this->region!="" && strlen($this->region)==2) { $data_location .= "&region=".$this->region; }
$data = file_get_contents($data_location);
$data = json_decode($data);
if ($data->status=="OK") {
$lat = $data->results[0]->geometry->location->lat;
$lng = $data->results[0]->geometry->location->lng;
if ($this->geocodeCaching) { // if we to need to cache this result
$data = array(
"address"=>trim(strtolower($address)),
"latitude"=>$lat,
"longitude"=>$lng
);
$CI->db->insert("geocoding", $data);
}
}
return array($lat, $lng);
}
the thing is whatever th address i pass to the function it returns only (0,0) for latitude and longitude .
i passed the address like
$address = "colombo,sri lanka";
$address = "colombo,LK";
$address = "newyork,United states";
$address = "1/35 amunugama gunnena,kandy,sri lanka";
but every time it returns (0,0) ,
why is this , what is the address format i need to use , please help . thanks in advance .........
I am not sure what value and URL you are getting exactly, so I tried in the browser with your input URL
http://maps.google.com/maps/api/geocode/json?address=colombo,sri+lanka&sensor=true
which gives the correct result.
Make sure your URL is creating correctly.
To see the output for debug, you can print like
print_r ($data);
Also the suggestion is put the CodeIgniter in your tag list.
Your address format should be like this" 13 Telfer Court Rowville VIC 3178 Australia"
Try this one it worked for me

Categories