A PHPRunner application can use the browser Geolocation API to request the user’s current latitude and longitude. Those coordinates can then be passed to the server and used for features such as nearby results, maps, service-area checks or location-aware filtering.
The basic flow is:
- Request the user’s location in JavaScript.
- Read the latitude and longitude returned by the browser.
- Send those values to the server.
- Store or use the coordinates in the PHPRunner application.
Before you start
Browser geolocation requires the user’s permission. The browser may display a prompt asking whether the user wants to share their location, and your application should continue to work if permission is denied.
Geolocation also requires a secure context. In production, the application should be served over HTTPS. Browsers generally allow geolocation on localhost for development as well.
The accuracy of the returned coordinates depends on the user’s device and environment. A phone with GPS may provide a very accurate location, while a desktop computer may return a less precise estimate based on Wi-Fi or other available information.
1. Request the user’s location
Add the following code to the JavaScript OnLoad event of the page where you want to request the user’s location. The Login or Menu page can be a convenient choice if you want the coordinates available throughout the user’s session.
The browser calls locationFound() when a location is available. The latitude and longitude are then posted back to the current application page.
The error callback is important because location access is never guaranteed. The user can deny permission, the device may be unable to determine its location, or the request may take too long.
2. Store the coordinates on the server
The following example stores the coordinates in session variables. Add it to the AfterAppInit event.
PHP
It is better to check whether the values were actually supplied instead of simply testing them as true or false. Latitude or longitude can legitimately be zero.
C#
3. Use the location elsewhere in the application
Once the coordinates are stored in the session, they can be used by other pages and events in the application.
For example, the PHP values are available as:
You could use these coordinates to:
- show locations nearest to the current user;
- calculate the distance to stores, offices or service locations;
- display the user’s approximate position on a map;
- filter records to a geographic service area;
- save the location together with a newly created record.
Optional: store the coordinates in the database
Session variables are useful when the location only needs to be available temporarily. If the location should be associated with a user, order, visit or another record, save the coordinates to the appropriate database fields instead.
For example, after obtaining the coordinates you could use PHPRunner’s Database API to update a record:
Adapt the table name, field names and key value to your own database structure.
Privacy and user experience
Location data can be sensitive, so request it only when the application has a clear reason to use it. It is usually better to request location at the point where it provides an obvious benefit rather than asking every visitor immediately after opening the application.
Your application should also have a fallback for users who decline location access. Depending on the use case, this might be a manually entered address, ZIP code, city or other location selection.
The browser Geolocation API gives PHPRunner applications a straightforward way to add location-aware functionality. The main considerations are permission, HTTPS, error handling and deciding how the coordinates should be used once they reach the server.
How to get the closest lat , long of this code from the database would help us use it. otherwise it is useless.
How to put a reset button to reload position into the field
Awesome code – the trouble for me was that it only stored the Lat/Long in the session variables once – so they got stuck there. This code in the Javascript Page Load refreshes those session variables every time
function OnPageLoad(pageObj,pageid,proxy,row)
{
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
//use proxy to store lat and lon in session variables on server
$.post(“menu.php”,{
lat:pos.coords.latitude,
lng:pos.coords.longitude
})
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
var watchID = navigator.geolocation.watchPosition( success, error, options );
var timeout = setTimeout( function() { navigator.geolocation.clearWatch( watchID ); }, 5000 );
//call get position with options that force a recently aquired location
navigator.geolocation.getCurrentPosition(success, error, options);
//probably not nesessary too lazy to take it out –
function showPosition(position) {
$.post(“menu.php”,{
lat:position.coords.latitude,
lng:position.coords.longitude
})
}
}
I learned it hard way that this method requires page to be loaded twice at first to set coordinates in session variables of longitude and latitude. How can I get the variables in one go? or am I wrong?