Map Scripting


Create Location-based Web Applications

iPhone “watchposition,” But Only If The Location Has Changed

As I’ve written previously iPhone geolocation using JavaScript is quite easy. In addition to grabbing the location once, you can use the W3C geolocation standard watchposition to get continual updates of the user’s location.

However, you can’t control how often you receive updates. On an iPhone, it sends new positions about once per second. To most web apps, that’s way too often, especially if the user isn’t moving much. The code below only performs the desired action when the new position is different enough than the last position. “Different enough” is 0.1 kilometers, but you can change that to whatever you want in the okdist variable.

This example is built on Mapstraction (as is much of Map Scripting 101), so you can use Google Maps, Bing, MapQuest, or any number of mapping providers. This code works on the iPhone, Android and many desktop browsers. Check out the code below, or see the working demo here.

// Pre-declare variables
var lastloc = mxn.Mapstraction.LatLonPoint(0, 0);
var okdist = 0.1; // km
// Request location updates

function foundLocation(position)
	var lat = position.coords.latitude;
	var lon = position.coords.longitude;
	var posll = new mxn.LatLonPoint(lat, lon);
	if (lastloc.distance(posll) > okdist) {
		lastloc = posll;
		// Your code for when new location is different enough


Category: How-tos


61 Responses

  1. Perry says:

    lillian@rumford.advances” rel=”nofollow”>.…


  2. rodney says:

    falls@powdered.buoyancy” rel=”nofollow”>.…

    ñïàñèáî çà èíôó….

  3. Barry says:

    conjugate@indefinitely.anhwei” rel=”nofollow”>.…


  4. craig says:

    jesuit@shear.piazza” rel=”nofollow”>.…


  5. dale says:

    flagellation@cavalry.heightening” rel=”nofollow”>.…


  6. Alexander says:

    adele@absently.per” rel=”nofollow”>.…


  7. Eduardo says:

    karshilama@plumbing.jumping” rel=”nofollow”>.…

    ñïñ çà èíôó!…

  8. cory says:

    concert@shay.establishing” rel=”nofollow”>.…


  9. tom says:

    religiously@cinches.principle” rel=”nofollow”>.…

    tnx for info….

  10. Louis says:

    charmingly@coccidioidomycosis.beccaria” rel=”nofollow”>.…

    ñýíêñ çà èíôó!…

  11. hugh says:

    fancies@civilian.amp” rel=”nofollow”>.…

    thank you….

Leave a Reply

Adam DuVanderHi, I'm Adam. I'm writing a book about developing maps on the web. This site is where I'll share the things I find and help you create your own maps. Find out more.

Map Scripting 101