how to get latitude and longitude from address in php code example

Example 1: get lat long from address php

<?php
$address = "Kathmandu, Nepal";
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&key=apikey';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
$responseJson = curl_exec($ch);
curl_close($ch);

$response = json_decode($responseJson);

if ($response->status == 'OK') {
    $latitude = $response->results[0]->geometry->location->lat;
    $longitude = $response->results[0]->geometry->location->lng;

    echo 'Latitude: ' . $latitude;
    echo '<br />';
    echo 'Longitude: ' . $longitude;
} else {
    echo $response->status;
    var_dump($response);
}    
?>

Example 2: get city name from latitude and longitude in php using geocode api

var x=document.getElementById("demo");
function getLocation(){
    if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else{
        x.innerHTML="Geolocation is not supported by this browser.";
    }
}

function showPosition(position){
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    displayLocation(lat,lon);
}

function showError(error){
    switch(error.code){
        case error.PERMISSION_DENIED:
            x.innerHTML="User denied the request for Geolocation."
        break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
        break;
        case error.TIMEOUT:
            x.innerHTML="The request to get user location timed out."
        break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="An unknown error occurred."
        break;
    }
}

function displayLocation(latitude,longitude){
    var geocoder;
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude);

    geocoder.geocode(
        {'latLng': latlng}, 
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    x.innerHTML = "city name is: " + city;
                }
                else  {
                    x.innerHTML = "address not found";
                }
            }
            else {
                x.innerHTML = "Geocoder failed due to: " + status;
            }
        }
    );
}

Example 3: how to get latitude and longitude from form in php

<!DOCTYPE html>

<html>

<form method="post">

<input type="text" name="address">

<input type="submit" name="submit" value="submit">

</form>

</html>

<?php

if(isset($_POST['submit']))

{


function getLatLong($address){

    if(!empty($address)){

        //Formatted 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

        $data['latitude']  = $output->results[0]->geometry->location->lat; 

        $data['longitude'] = $output->results[0]->geometry->location->lng;

        //Return latitude and longitude of the given address

        if(!empty($data)){

            return $data;

        }else{

            return false;

        }

    }else{

        return false;  
 
    }

}

$address = $_POST['address'];

$latLong = getLatLong($address);

$latitude = $latLong['latitude']?$latLong['latitude']:'Not found';

$longitude = $latLong['longitude']?$latLong['longitude']:'Not found';

echo "Latitude:".$latitude."<br>";

echo "longitude:".$longitude."";

}

?>

Tags:

Html Example