Map Scripting

Icon

Create Location-based Web Applications

How to Add Custom Markers to Your Map

It might be the best way to make your map look different than all the others. Lose the reverse tear drop icons (the default Google look) and add your own graphics.

Mapstraction makes it easy to include your own markers. And, as always, write the code once in Mapstraction and it works in one of a dozen mapping APIs. Here’s a custom marker map demo that shows a sombrero over my favorite Mexican restaurant in Portland. Classy!

It looks something like this:
Custom sombrero marker

Now you try:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Custom Marker Map</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YOURKEY"
    type="text/javascript"></script>
    <script src="mapstraction.js"></script>
    <style>
      div#mymap {
        width: 400px;
        height: 350px;
      }
    </style>
    <script type="text/javascript">
      var mapstraction;
function create_map() {
  mapstraction = new Mapstraction('mymap', 'google');
  mapstraction.setCenterAndZoom(
    new LatLonPoint(45.559242, -122.636467), 15);
  var mk = new Marker(new LatLonPoint(45.559242, -122.636467));
  mk.setIcon('sombrero.png', [40,24]);
  mk.setShadowIcon('sombrero-shadow.png', [53,24]);
  mapstraction.addMarker(mk);
}
    </script>

  </head>
  <body onload="create_map()">
    <div id="mymap"></div>
  </body>
</html>

Remember you’ll need to download Mapstraction and get a Google Maps API key. Finally, make sure you have the following if you plan on using the sombrero images:

Happy mapping with your custom markers!

Geolocate Now With Twitter, Using Simple Search

While we’re waiting for Twitter’s official geolocation platform, how about this ad hoc method. Pick a famous location, stick “at” in front of it, and use Twitter search.

Tweets from Disneyland

Amber Case suggested Disneyland. Go ahead and try it out. I found that Graceland and Yellowstone have good results, too.

We’ll be able to do more interesting things when we have latitude and longitude. In the meantime, this is a fun, simple way to get a glimpse of what’s going on at popular vacation destinations.

Zoom in on Mapping and Location

I was delighted to speak at DevGroupNW, giving an overview of mapping and location services. I covered four areas: mapping APIs, geocoders, location guessing and location sharing. The areas are all inter-related, with location data eventually finding its way to a map.

I’ve posted my slides (also embedded below):

I’ll finish this post by asking the same question I did of the audience: how will you use location in your web projects?

How to Use iPhone JavaScript Geolocation

Update: iPhone OS 3.0 is now out. I have updated the code below to the latest geolocation spec, which the iPhone supports.


There will soon be a new iPhone and a third version of the phone’s operating system. Among the new features in iPhone OS 3.0 is geolocation in the web browser, which will be available on all iPhones–not just the new one. As a developer who appreciates the single platform of the web, this is the most exciting news.

I’ve had a number of people suggest that I should create an iPhone app for my Portland WiFi finder site. While I like the idea of being able to immediately show closest hotspots, it seems like a lot of work for a small number of users (sorry Portland laptoperati).

Plus, I love the web. It is my favorite platform. Geolocation in a simple browser is becoming more common, though it usually involves installing an add-on. I expect that will change, with browsers incorporating geolocation just as Apple has with the iPhone. The Opera browser has already done this and Firefox’s next version will, too.

There is even a W3C standard for geolocation being developed. From the looks of Apple’s documentation, the iPhone supports the specification, which adds a navigator.geolocation object.

You can try it out on your iPhone by going to this shortened URL:
http://bit.ly/w3cgeo

Here’s code for finding the location of your user in the iPhone 3.0 version of Safari:

navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

function foundLocation(position)
{
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  alert('Found location: ' + lat + ', ' + long);
}
function noLocation()
{
  alert('Could not find location');
}

The getCurrentPosition function requires two arguments, which are each function references. You can write them as inline, anonymous functions, or name them as I have above.

Upon success, the first function will be called. As you can see, an object containing the latitude and longitude is passed to this function. My code just echos the data in an alert, but yours will likely center a map or lookup nearby locations.

As with any geolocation, the user will have to give permission to provide the location data. If they deny, or if there is an error, the second function is called. Use this function to perform any tasks necessary for a non-geolocated user. I send a message through an alert, but you probably won’t want to do this.

Native geolocation on the iPhone should get the feature more respect and pick-up in all browsers. Hopefully Google Gears, which also provides this feature to browsers and mobile phones, will adopt the W3C spec so that we have one, standard way to access geo data.

Roll Your Own IP Geocoder

If you’ve ever seen a site correctly guess your location, chances are good it used your IP address and a big ol’ database to make an educated stab at it. Now you can do the same and do it for free.

IP addresses are numeric identifiers for every computer connected to the Internet. They look like 68.180.206.184 and 206.190.60.37. With great accuracy, these can be traced down to the city where they originate, assuming you have the data necessary.

Marc-Andre Caron compiled a MySQL IP database that you can install on your own server. Read on for some basic instructions to roll your own geocoder. If you’d rather use a web service to get at the data, check out my post at ProgrammableWeb.

Wait… How Does This Work?

The database catalogs known blocks of IPs by their location. For example, Comcast cable might own 71.59.208.0 – 71.59.208.255 and use them (along with many others) to hand out to Portland residents.

To conserve database space, the IP is converted to a unique number. Where the IP is A.B.C.D, the number is ((A*256+B)*256+C)*256. So, 71.59.208.255 would become 1195102208. As would anything in the 71.59.208.X block, because notice that there is no D in the above formula. That’s because IPs come in blocks, so everything in the range will likely have the same location.

Download and Decompress the Database
Caron’s MySQL database comes compressed using bzip2, a free utility available on most Unix-ish systems. While phpMyAdmin accepts imports directly in the compressed format, it is likely beyond the capacity, so you will need to have SSH access to your server and the MySQL command tool.

Download the SQL to your server and unzip the archive:
bunzip2 ipinfodb.sql.bz2

You should now have a much larger file, likely called ipinfodb.sql.

Install the Database

Now you’ll need to use the MySQL tool on your server. You may need to ask your host for specifics, but often the command to bring it up will be similar to this:
mysql -u username -p databasename

You’ll be asked for a password. If all is well, you’ll see the prompt, where you can enter SQL commands. This is a less graphical phpMyAdmin, a great place to test out queries.

To import the data, run this command in the MySQL tool:
\. ipinfodb.sql

This will read in the large SQL file and start creating the tables and adding its necessary data. The process will take many minutes. Go take a break!

When you see the MySQL prompt again, you know it is finished. To quit the tool, use the \q command.

Run a Lookup from PHP

There are two ways to query the database. You can convert the IP to a number yourself, or you can use the INET_ANON function in MySQL:
SELECT * FROM `ip_group_city` where `ip_start` <= INET_ATON('71.59.208.255') order by ip_start desc limit 1

The PHP code below shows both options. Before you add it to your own server, see it in action. If you remove the query string (that stuff after the question mark) you can geocode your own IP.

Here is the code listing for my example PHP (be sure to fill in your DB values at the top):

<?
  // Config values -- FILL THEM IN
  $dbserver = "";
  $dbname = "";
  $dbuser = "";
  $dbpass = "";

  // Setup variables
  $ip = $_GET["ip"];
  if ($ip == "") { $ip = $_SERVER["REMOTE_ADDR"]; }
  list($lat, $lon)  = lookup_ip($ip);
  if ($lat && $lon) {
    print "$lat, $lon";
  }

function lookup_ip($ip) {
  global $dbserver, $dbuser, $dbpass, $dbname;
  if (!preg_match("/^\d+\.\d+\.\d+\.\d+$/", $ip)) {
    return;
  }
  $d = mysql_connect($dbserver, $dbuser, $dbpass);
  mysql_select_db($dbname, $d);
  $ipnum = ip_to_number($ip);
  // The numeric option...
  $s = "select latitude, longitude from ip_group_city where ip_start";
       $s .= "<= $ipnum order by ip_start desc limit 1";
  // Or the INET_ANON option...
  $s = "select latitude, longitude from ip_group_city where ip_start";
       $s .= "<= INET_ATON('$ip') order by ip_start desc limit 1";
  $res = mysql_query($s, $d);
  $ll = mysql_fetch_array($res, MYSQL_NUM);
  mysql_close($d);

  return $ll;
}
function ip_to_number($ip) {
  list($a, $b, $c, $d) = split("\.", $ip);
  return (($a*256 $b)*256 $c)*256;
}
?>

Maps Project: Automatic Street View Tour

Here’s a cool idea that Joe Lazarus wants to give to you. Joe made a video tour across the Golden Gate Bridge (embedded above). Since Google Maps gives API access to Street View, someone could automate the process and maybe even open it up to any route.

It sounds like just the thing I’d want to try out if I wasn’t busy writing a book about mapping APIs. Oh, the irony.

But, hey–here’s the Street View API documentation. Be sure and let me know when you’re finished.

Via Andy

Create Dynamic Numbered Markers for Google Maps

MapScripting markersWhen you’re plotting locations from a database or matching search results to markers on the map, you may want to add labels. For example, the closest locations on this WiFi hotspot are both listed and plotted, marking spots with numbers. Similarly, Google shows local search results with alpha labels, A-Z.

Previously, you had to download sets of markers. If you needed a marker you didn’t have, you needed to make a new one. Thanks to Google Charts, you can create dynamic labeled markers.

All it requires is passing the label in the URL. Pretty easy. You can also change the color of the marker and its border. Here’s the URL for the “A” marker:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=A|00CC99|000000

Even better, you can use the markers anywhere you find useful, including other mapping providers. An example of this using Mapstraction is in my book. If you’d like to see it in Google Maps proper, view the source of this sample map.

Which Maps API Should I Use?

Google, Yahoo, and Microsoft maps

Google Maps is the mashup mainstay, but it’s not the only game in town. You may prefer the deep red color of Yahoo Maps freeways or the bird’s eye view in Microsoft Live Earth.

My advice to those new to mapping is always the same: go with Mapstraction. It’s not an API itself, but a wrapper for about a dozen other mapping services. You can write once with Mapstraction and switch providers later on.

Say you choose Google Maps now (and most of us do). Down the line if Google chooses to put ads on the map, for example, you’d be able to switch to Yahoo with minimal changes to the underlying code.

There are some downsides to using Mapstraction. It is built to work with many providers, meaning that Mapstractions features can only be those shared by all mapping platforms. When Google releases a hip new feature, that might not be immediately available in Mapstraction. Nevertheless, for most common mapping projects, this won’t be an issue.

Get started with Mapstraction by reading my Mapstraction tutorial at Webmonkey.

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