Get current location coordinates php

The old freegeoip API is now deprecated and will be discontinued on July 1st, 2018.

The new API is from https://ipstack.com. You have to create the account in ipstack.Then you can use the access key in the API url.

$url = "http://api.ipstack.com/122.167.180.20?access_key=ACCESS_KEY&format=1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$city  = $response->city; //You can get all the details like longitude,latitude from the $response .

For more information check here :/ https://github.com/apilayer/freegeoip

In php, we can get the current location’s latitude and longitude from an address and also get an address from a latitude and longitude by leveraging the Google Maps API.

To get the latitude and longitude from an address, you can define a custom php function as shown below.

function getLatLong($address){
    $formatted_address = str_replace(' ','+',$address);
    $geocodeFromAddr = file_get_contents('//maps.googleapis.com/maps/api/geocode/json?address='.$$formatted_address.'&sensor=false');
    $output = json_decode($geocodeFromAddr);
    $data['latitude'] = $output->results[0]->geometry->location->lat;
    $data['longitude'] = $output->results[0]->geometry->location->lng;
    if(!empty($data)){
        return $data;
    } else {
        return false;
    }
}

print_r(getLatLong("44 E 161st St, Bronx, NY 10451"));

//Output: 
Array
(
    [latitude] => 40.827519
    [longitude] => -73.925879
)

To go the other way and get an address given longitude and latitude coordinates, you can define a custom php function as shown below.

function getAddress($latitude,$longitude){
    $geocodeFromLatLong = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($latitude).','.trim($longitude).'&sensor=false'); 
    $output = json_decode($geocodeFromLatLong);
    $status = $output->status;
    
    $address = ($status=="OK") ? $output->results[1]->formatted_address:'';
    if(!empty($address)){
        return $address;
    }else{
        return false;
    }
}

echo getAddress();

// Output:
44 E 161st St, Bronx, NY 10451, USA

When designing forms for our web pages in php, many times we are asking for an address.

After receiving an address, the ability to get the longitude and latitude to determine the location of an address can be useful.

The Google Maps Geocoding API allows us to find the longitude and latitude given an address.

We can leverage the Google Maps Geocoding API and define a function which takes in an address and returns the longitude and latitude.

Below is an example of how to get the coordinates given an address in php.

function getLatLong($address){
    $formatted_address = str_replace(' ','+',$address);
    $geocodeFromAddr = file_get_contents('//maps.googleapis.com/maps/api/geocode/json?address='.$$formatted_address.'&sensor=false');
    $output = json_decode($geocodeFromAddr);
    $data['latitude'] = $output->results[0]->geometry->location->lat;
    $data['longitude'] = $output->results[0]->geometry->location->lng;
    if(!empty($data)){
        return $data;
    } else {
        return false;
    }
}

print_r(getLatLong("44 E 161st St, Bronx, NY 10451"));

//Output: 
Array
(
    [latitude] => 40.827519
    [longitude] => -73.925879
)

How to Get the Current Location Given Longitude and Latitude in php

If you’d like to go the other way, and get an address given the longitude and latitude, we can adjust our function from above.

We will still use the Google Maps Geocoding API, but now, instead we will pass the longitude and latitude instead of a formatted address.

Below is an example of how to get an address given longitude and latitude in php.

function getAddress($latitude,$longitude){
    $geocodeFromLatLong = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($latitude).','.trim($longitude).'&sensor=false'); 
    $output = json_decode($geocodeFromLatLong);
    $status = $output->status;
    
    $address = ($status=="OK") ? $output->results[1]->formatted_address:'';
    if(!empty($address)){
        return $address;
    }else{
        return false;
    }
}

echo getAddress();

// Output:
44 E 161st St, Bronx, NY 10451, USA

Hopefully this article has been useful for you to get the current location and get the longitude and latitude from an address in php.


The HTML Geolocation API is used to locate a user's position.


Locate the User's Position

The HTML Geolocation API is used to get the geographical position of a user.

Since this can compromise privacy, the position is not available unless the user approves it.

Note:Geolocation is most accurate for devices with GPS, like smartphones.


Browser Support

The numbers in the table specify the first browser version that fully supports Geolocation.

API
Geolocation 5.0 - 49.0 (http)
50.0 (https)
9.0 3.5 5.0 16.0

Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.


Using HTML Geolocation

The getCurrentPosition() method is used to return the user's position.

The example below returns the latitude and longitude of the user's position:

Example

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

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

Try it Yourself »

Example explained:

  • Check if Geolocation is supported
  • If supported, run the getCurrentPosition() method. If not, display a message to the user
  • If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)
  • The showPosition() function outputs the Latitude and Longitude

The example above is a very basic Geolocation script, with no error handling.



Handling Errors and Rejections

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

Example

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;
  }
}

Try it Yourself »


Location-specific Information

This page has demonstrated how to show a user's position on a map.

Geolocation is also very useful for location-specific information, like:

  • Up-to-date local information
  • Showing Points-of-interest near the user
  • Turn-by-turn navigation (GPS)

The getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object on success. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:

PropertyReturns
coords.latitude The latitude as a decimal number (always returned)
coords.longitude The longitude as a decimal number (always returned)
coords.accuracy The accuracy of position (always returned)
coords.altitude The altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracy The altitude accuracy of position (returned if available)
coords.heading The heading as degrees clockwise from North (returned if available)
coords.speed The speed in meters per second (returned if available)
timestamp The date/time of the response (returned if available)

Geolocation Object - Other interesting Methods

The Geolocation object also has other interesting methods:

  • watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
  • clearWatch() - Stops the watchPosition() method.

The example below shows the watchPosition() method. You need an accurate GPS device to test this (like smartphone):

Example

<script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}
function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

Try it Yourself »



How can I get latitude and longitude from address in PHP?

Function Usage: php $address = 'Brooklyn, NY, USA'; $address = str_replace(' ', '+', $address); $result = getGeoCode($address); echo 'Latitude: ' . $result['lat'] . ', Longitude: ' . $result['lng']; // produces output // Latitude: 40.6781784, Longitude: -73.9441579 ?>

How can get current location in HTML?

To get the user's current location, getCurrentPosition() method of the navigator.

How do you get current location on Web application?

Follow these steps :.
Create a Webscreen..
go to the sidebar javascript option and add this js code over there : if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(getPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } ... .
Now publish and check it..

How do I find my current latitude and longitude?

Android: Open Google Maps; it will zoom to your approximate location. Press and hold on the screen to drop a pin marker. Click on the dropped pin; latitude and longitude will be displayed below the map.