- How Does GeoLocation Work?
- Building a Simple Script
- Advancing GeoLocation
- Browser Support
Building a Simple Script
Let’s take a look at a very basic script that displays the user’s longitude and latitude.
First, you want to check if the browser supports GeoLocation:
if (navigator.GeoLocation) { // make sure browser supports GeoLocation // stuff to go here later }
The first line executes the core method that retrieves the user’s position (getCurrentPosition):
if (navigator.GeoLocation) { // make sure browser supports GeoLocation navigator.GeoLocation.getCurrentPosition(show_coordinates); // more stuff to go here later }
Once the user agrees to share her position, the show_coordinates function displays an alert box that reveals the user’s coordinates, as shown in Figure 5.
if (navigator.GeoLocation) { // make sure browser supports GeoLocation navigator.GeoLocation.getCurrentPosition(show_coordinates); function show_coordinates(position){ alert('Your latitude is ' + position.coords.latitude + ' ' + 'and your longitude is ' + position.coords.longitude + '.'); } }
Figure 5 The alert box shows the latitude and longitude.