Mapping your web server visitors in Google Earth, Part 3 (conclusion)

No Gravatar

A few days later, but here’s the conclusion to the story. In part 2, I showed how to parse out the apache log file to get a list of IP addresses. Now all you have to do is, one by one, geolocate those addresses and write them out to a KML doc that gets displayed in Google Earth (or even Google Maps).
For geolocating, I’m using the free product by MaxMind (http://www.maxmind.com/app/ip-location) to do the lookups for the geolocation. Here’s the code to do the geolocation and write out to KML.


import com.maxmind.geoip.*;
import java.io.*;

/* sample of how to use the GeoIP Java API with GeoIP City database */
/* Usage: java CityLookupTest 64.4.4.4 */

class CityLookup {
    public static void main(String[] args) {
        try {
            LookupService cl = new LookupService(args[0],
                    LookupService.GEOIP_STANDARD);
            BufferedReader in = new BufferedReader(new FileReader(args[1]));
            BufferedWriter out = new BufferedWriter(new FileWriter(args[2]));
            String str;

            out.write("<?xml version="1.0" encoding="UTF-8"?>n");
            out.write("<kml xmlns="http://earth.google.com/kml/2.1">n");
            out.write("<document>n");
            while ((str = in.readLine()) != null) {
                Location loc = cl.getLocation(str);
                if (loc == null) {
                    System.out.println("loc null");
                } else {
                    out.write(" <placemark>");
                    out.write("<name>" + str + "</name>");
                    out.write("<description>" + str + "</description>");
                    out.write("<point>");
                    out.write("<coordinates>" + loc.latitude + ","
                            + loc.longitude + "</coordinates>");
                    out.write("</point>");
                    out.write("</placemark>n");
                }
            }
            in.close();
            out.write("</document>n");

            out.write("</kml>n");
            out.close();
            cl.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Now, all you have to do is import the file into Google Earth, or if you have a publicly available web server, you can put the file there, and have google maps pick it up by passing the file as a parameter.
I hope you’ve enjoyed reading this 3-part tutorial as much as I’ve enjoyed writing it. This could be the start of a fun project. Hope you enjoy!

Part 2

Part 1

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *