Friday 30 October 2015

How to calculate latitude and longitude for a given address and vise-versa in php

Hi Everybody,

In this blog we will discuss about how to calculate latitude and longitude for a given address and vise-versa in php.

Get latitude and longitude from a  given address(Geocode):-


        $address = "790 Castro St, Mountain View, CA";

        $formAddr = str_replace(' ','+',$address);

        $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formAddr.'&sensor=false');

        $output= json_decode($geocode);

        if(is_array($output )&& $output ['Status']['code']==200) {

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

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

       }

Get address from latitude and longitude(Reverse Geocode):-


       $lat = 37.3874353;
        $lng = -122.0835459;
        $revGeocode = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false");
        $output = json_decode($revGeocode);
        if(is_array($output )&& $output ['Status']['code']==200) {
                    $address = $output->results[0]->formatted_address;
        }

Let me know if you face any problem in this.
Thanks.

No comments:

Post a Comment