With this particular API, we can create many innovative and useful location-based services and mobile apps such as ATM finders, cafe & restaurants locator or you can request a taxi from your current location.
User will be prompt with a pop-up message box asking their permission when you are using Geolocation API.
Remember that this API is only available for HTML5. Thus, you must declare at the very top of the HTML page.
Today, I am creating a simple page that use the HTML5 Geolocation API as below:
Below are working sample HTML5 code together with Geolocation API usage:
<!DOCTYPE HTML><html><head><meta charset="utf-8"><title>HTML5 Geolocation API</title></head><body><img id="GoogleMap" /><p id="locationInfo"></p>
<script>var img = document.getElementById('GoogleMap');var info = document.getElementById('locationInfo');
//The Geolocation APInavigator.geolocation.getCurrentPosition(successGetPosition,failToGetLocation);
//Successfully get device's locationfunction successGetPosition(position){var latitude = position.coords.latitude;var longitude = position.coords.longitude;var timeStamp = new Date(position.timestamp);// Display GPS infoinfo.innerHTML = 'Latitude: '+latitude+'<br />'+'Longitude: '+longitude+'<br />'+'Timestamp: '+timeStamp+'<br />';// Display Google Mapimg.src = "http://maps.google.com/maps/api/staticmap?sensor=true&"+"center="+latitude+","+longitude+"&zoom=13&size=295x295&markers=color:green|"+latitude+","+longitude;}
// Function to handle error to get GPS infofunction failToGetLocation(error){var displayTxt;switch(error.code){case error.PERMISSION_DENIED:displayTxt = 'Permission denied'; break;case error.POSITION_UNAVAILABLE:displayTxt = 'Position unavailable'; break;case error.TIMEOUT:displayTxt = 'Position lookup timeout. Please try again later.'; break;default: displayTxt = 'Unknown position';}info.innerHTML = displayTxt;}</script>
</body></html>
PS: Happy geotagging!
No comments:
Post a Comment