This tutorial is prepared for those Developers who want to get users latitude and longitude. This can be done by many methods, here I’m going to use Google Place API to make such things easier.
The method and logic I’m going to use is when user fills the registration form up, we’d capture his city value (Note: city value would be Google Place Search), before proceeding further you have to read my previous post Auto complete Address Search Module Using Google API and PHP, this is the module from which we ask user to enter their location, further this location is used to capture user’s coordinates using another Google API.
It is not all mandatory to use address search module, you can use manual address as well.
What are Latitude and Longitude?
Latitude and Longitude are the entity that represents the coordinates at the geographic coordinate system.
For example, every actual house has its own address (which includes the house number, the street name, city, country, etc), every single dot on the surface of the earth can be specified by the latitude and longitude coordinates.
Therefore, by using these coordinates we can specify virtually any point on earth.
How to get users latitude and longitude?
Step 1: after submitting registration form catch the user’s current location value (read Auto complete Address Search Module Using Google API and PHP to understand
$location variable below).
$location = $_POST['location'];
Step 2: make a request to google place API
$data = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($location)."&sensor=true"); $longitude = json_decode($data)->results->geometry->location->lng; $latitude = json_decode($data)->results->geometry->location->lat;
as you can see the above variables $longitude & $latitude store user’s exact coordinates. You can use these variables as anyway as you want.
NOTE: If you want to store these coordinates into the database, you must have to create longitude and latitude column with datatype double.
Please share this article with your friends, and get in touch because we are going to post lots of interesting and helpful modules in future, don’t forget to subscribe us to get latest updates.
You may also like
Please help us by showing your reaction
You can also use HTML5 Geo Location to get lat and long of the user.
yeah you’re right, but user will be asked for to allow their location (popup).
It is showing the following error
Trying to get property ‘geometry’ of non-object in