First off, test the browser for support of HTML 5 Geolocation. The first call to get the location of the client / user will also prompt a dialog that the user must usually confirm to to allow getting the location.
The following Javascript is necessary to get the latitude and longitude of the client :
function getLocation() { if (navigator.geolocation){ var position = navigator.geolocation.getCurrentPosition(showPosition); } } function showPosition(position){ console.log(position); $("#demo").html(position.coords.latitude + " " + position.coords.longitude); }
Note that you can retrieve additional information such as altitude, heading and speed if the client got positioning hardware supporting this.
Mozilla Developer Network - Coordinates object
In Firefox, you have to use HTTPS to use Geolocation in newer versions of this browser. The client must agree to share the current location. A demo of Geolocation is here:
HTML 5 Geolocation demo - Plunk
Let us also use a map to show the location of the user. We can use Google Maps API. To use this API, request a Google API Key from here:
Google API Key site
We plot the current location with some script below using the Google Maps API, adding a Marker that is bouncing on top of the current location.
function getLocation() { if (navigator.geolocation){ var position = navigator.geolocation.getCurrentPosition(showPosition); } } function showPosition(position){ var mapCanvas = document.getElementById("demo"); var myCenter = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var mapOptions = {center: myCenter, zoom: 12}; var map = new google.maps.Map(mapCanvas,mapOptions); var marker = new google.maps.Marker({ position: myCenter, animation: google.maps.Animation.BOUNCE }); marker.setMap(map); }
The current location is displayed using Google Maps as displayed here:
Support for Geolocation in Firefox is limited to HTTPS and recent version of Firefox may not function with Geolocation in Linux, newer than Firefox version 20. If so, downgrade to Firefox Version 20. I have tested the code above using Opera web browser in Linux Mint 15.
Note that we here added Google Maps Javascript source reference and an Google API key.
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAeymq4mlrbKoBUhU3LdegaudQDnY7MFPo&callback=myMap"></script>
No comments:
Post a Comment