What if I want to know how to get to Australia from home? And what if I don't know where I live? I worry no more, for Geolocation api and Google Maps api have an answer for me (and my lazyness)

Geolocation And Routes With Google Maps

One of my dream projects is modeling Mexico city transit on real streets. This is a very serious project if you come to think about it:

  • You need up to date maps of all Mexico City.
  • Once such maps are collected, you need real statistics about the number of vehicles transiting, and porcentages regarding what type of vehicles they are.
  • Next step is modeling several types of behavior for every type of vehicles, including (but not limited to) average speed, max speed, acceleration, probability of violating driving laws, probability of wrecking, probability of causing an accident... I can't even think of all of them.
  • External behaviours, like traffic light and pedestrians.
  • Giving your virtual cars the ability to run through the road (some vector math and heuristic path finding algorithms (as A*) should be helpful here, in fact that's what I use in an early implementation).
  • Deciding what route to take.

I could elaborate on these points and the list would look amazingly big. Luckily, I am befriended with Dr. Nicolás Dominguez-Vergara from Instituto Mexicano Del Petróleo, so I get the statistics for free.

As most of you may know, Google offers its service (and api) Google Maps practically free. It supports several features, but the ones that I'm interested the most are 1) the ability to fetch and show maps from practically every corner of the city and 2) the ability to trace routes between two (ok maybe more) points in the map.

But what about the up to date maps? what about planning routes? Well, that's where Google comes to the recue!

Let's go directly to the source, luke:

function initGoogleMaps(){
    var options = {
        zoom: 15,
        center: p1,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        streetViewControl: false
    };

    directionsDisplay = new google.maps.DirectionsRenderer();

    map = new google.maps.Map(document.getElementById("map"), options);

    directionsDisplay.setMap(map);

    var marker1 = new google.maps.Marker({
        position: p1,
        title:"Dirección 1"
    });

    // To add the marker to the map, call setMap();
    marker1.setMap(map);

    var marker2 = new google.maps.Marker({
        position: p2,
        title:"Dirección 2"
    });

    // To add the marker to the map, call setMap();
    marker2.setMap(map);

    document.getElementById("p1").innerHTML = p1;
    document.getElementById("p2").innerHTML = p2;

    calRoute();
}

Here we start initializing Google Maps and a direction renderer, cuz that's what we want right? Find and display a route. We procceed to add a marker in the map in our current position (we'll talk about that in short) then a second marker, and finally we calculate the route.

As we can see, the api for showing a Google Map (in this case, inside the div called "map") is pretty simple. It is too simple for calculating routes between two points, let's check that.

function calRoute(){
    var direction = {
      origin: p1,
      destination: p1,
      //travelMode: TravelMode.DRIVING,
      //unitSystem: UnitSystem.METRIC,
      //waypoints[]: DirectionsWaypoint,
      //optimizeWaypoints: Boolean,
      //provideRouteAlternatives: Boolean,
      //avoidHighways: Boolean,
      //avoidTolls: Boolean
      //region: String
    }

    var request = {
        origin: p1, 
        destination: p2,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
}

See? easy! we define a direction object, using our two points p1 and p2 as origin and destination, respectively. The last part is asking for the route to Google Direction Service, and that's it!

Ok, so far so good. But what about the point p1 and p2? Where do they come from? p2 is hardcoded to some random point in Australia because I want to know how to get there, from any point I could be in. Any one. Geolocation api to the recue!

Let's jump directly into the code (don't worry, it's pretty quick):

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position){
        p1 = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        initGoogleMaps();
    }, 
    function(){
        initGoogleMaps();
    });
}

Here we just check for geolocation api availability and take p1 from the result. Easy peasy!

I hope someone find this useful. Here is a working (and ugly) demo. Peace out!

Posted by: fabzter
Last revised: 08 Jan, 2014 11:55 PM History

Comments

PREGUNTON
PREGUNTON
20 Jul, 2015 07:02 AM

more demos working ? great!

13 Feb, 2017 11:24 PM

amigo, vc poderia me ajudar? preciso pegar quantos quilometros tem o percurso, e o tempo aproximado

Your Comments

Used for your gravatar. Not required. Will not be public.
Posting code? Indent it by four spaces to make it look nice. Learn more about Markdown.

Preview