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;
}
}
}
Related
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
I have a query to my pgsql table which should return several responses. In fact, it does in pgAdmin. However, when I run it through php and convert to lat, long using google apis I am getting empty brackets in the response. Does anyone see what I may be doing wrong, it was working up till yesterday and I was doing some tweaking to the code. I may have inadvertently done something wrong.
Here is the query and subsequent conversion in php...
$address = pg_query($conn, "
SELECT
CONCAT(incident.city, ' ' , incident.state_1)
FROM
fpscdb001_ws_001.incident
WHERE
incident.initial_symptom = 'Chrome Upgrade' AND
incident.status_1 = 'staging' AND
incident.site_id != '2RS'
;");
if (!$address) {
echo "Query failed\n";
exit;
}
$arr = array();
while ($coordsred = pg_fetch_row($address)){
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$coordsred[0]."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK") {
$Lat = (float)$xml->result->geometry->location->lat;
$Lng = (float)$xml->result->geometry->location->lng;
$arr[] = array("lat" => $Lat, "lng" => $Lng);
}
}
echo json_encode($arr);
This is the companion javascript that calls the php...
var xhrred = new XMLHttpRequest();
xhrred.onreadystatechange = function() {
if (xhrred.readyState == 4) {
var arrred = JSON.parse(xhrred.responseText);
console.log(xhrred.responseText);
if(Array.isArray(arrred)){
showMarkersRed(arrred);
}
}
}
xhrred.open('GET', 'markersred.php', true);
xhrred.send();
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;
}
}
I would like to get country, region and city name from longitude and latitude over Google maps API (V3?) - with PHP. I just can't manage to get it for every county, I managed to get this code but it doesn't work on other counties because the returned result is different (the only correct information is country but even that is returned in local name not English name):
<?
$lok1 = $_REQUEST['lok1'];
$lok2 = $_REQUEST['lok2'];
$url = 'http://maps.google.com/maps/geo?q='.$lok2.','.$lok1.'&output=json';
$data = #file_get_contents($url);
$jsondata = json_decode($data,true);
if(is_array($jsondata )&& $jsondata ['Status']['code']==200)
{
$addr = $jsondata ['Placemark'][0]['AddressDetails']['Country']['CountryName'];
$addr2 = $jsondata ['Placemark'][0]['AddressDetails']['Country']['Locality']['LocalityName'];
$addr3 = $jsondata ['Placemark'][0]['AddressDetails']['Country']['Locality']['DependentLocality']['DependentLocalityName'];
}
echo "Country: " . $addr . " | Region: " . $addr2 . " | City: " . $addr3;
?>
This works great to get correct data from my country, but not for others...
You can use second api(suggested by Thomas) like this:
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=48.283273,14.295041&sensor=false');
$output= json_decode($geocode);
echo $output->results[0]->formatted_address;
Try this..
Edit:::::
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=48.283273,14.295041&sensor=false');
$output= json_decode($geocode);
for($j=0;$j<count($output->results[0]->address_components);$j++){
echo '<b>'.$output->results[0]->address_components[$j]->types[0].': </b> '.$output->results[0]->address_components[$j]->long_name.'<br/>';
}
Here is my approach to the problem
$lat = "22.719569";
$lng = "75.857726";
$data = file_get_contents("http://maps.google.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false");
$data = json_decode($data);
$add_array = $data->results;
$add_array = $add_array[0];
$add_array = $add_array->address_components;
$country = "Not found";
$state = "Not found";
$city = "Not found";
foreach ($add_array as $key) {
if($key->types[0] == 'administrative_area_level_2')
{
$city = $key->long_name;
}
if($key->types[0] == 'administrative_area_level_1')
{
$state = $key->long_name;
}
if($key->types[0] == 'country')
{
$country = $key->long_name;
}
}
echo "Country : ".$country." ,State : ".$state." ,City : ".$city;
<?php
$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;
?>
Have you tried using their GeoCoding API?
https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
Example:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
Edit: I have used it in many apps targeting India and it has worked pretty well.
its really stupid to always depend on google.
put the cities into text file with GPS x and Y coorindates and pull from there. all of this is available online
if you use laravel then it will usefull for you
$latitude=26.12312;
$longitude=83.77823;
$geolocation = $latitude.','.$longitude;
$response = \Http::get('https://maps.googleapis.com/maps/api/geocode/json', [
'latlng' => $geolocation,
'key' => 'api key',
'sensor' => false
]);
$json_decode = json_decode($response);
if(isset($json_decode->results[0])) {
$response = array();
foreach($json_decode->results[0]->address_components as $addressComponet) {
$response[] = $addressComponet->long_name;
}
dd($response);
}
please replace api key with your own
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 .= "®ion=".$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