Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
From the author of Building a Simple Script

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.

  • + Share This
  • 🔖 Save To Your Account