JavaScript Geolocation
Geo Location
Browser supports to get geolocation using javascript.
This is an example code for it.
But, to get geolocation, the user accept to get with select dialog(permission).
Example
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Geo</title> <script src="./geo.js" type="text/javascript"></script> </head> <body> <script>geo();</script> </body> </html>
geo.js
function geo() { if (navigator.geolocation) { // Can get location var option = { "enableHighAccuracy": false, "timeout": 5000, "maximumAge": 5000, }; navigator.geolocation.getCurrentPosition(function(position){ var data = position.coords; var lat = data.latitude ; var lng = data.longitude ; var alt = data.altitude ; var accLatlng = data.accuracy ; var accAlt = data.altitudeAccuracy ; var heading = data.heading ; var speed = data.speed ; alert("Latitude : " + lat + " Longitude :" + lng); }, function(error) { // 0: UNKNOWN, // 1: PERMISSION_DENIED // 2: POSITION_UNAVAILABLE, // 3: TIMEOUT alert("Error"); }, option); } else { // Cannot get location alert("Error"); } }
Press button and get geolocation data.
Before getting data, check object existence.
If missing, skip codes.