Friday, February 17, 2012

Adding markers for given locations

Today I'll cover the first example given in this documentation page. Try interacting with the map below. For the given scale, cities show up best in the map, although street addresses all the way to continent names will be recognized.

Click here to open

First, we have the standard header and JavaScript include for the Google Maps API.

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

Next, before defining the initialize() function, both map and geocoder variables should be declared global, because they will be called from more than one function. The geocoder is initialized with the map.

    <script type="text/javascript">
      var map;
      var geocoder;
      mapCenter = new google.maps.LatLng(39.11, 0.94);


      function initialize() {
        geocoder = new google.maps.Geocoder();
        map = new google.maps.Map(document.getElementById("map_canvas"),
        { center: mapCenter, 
          zoom: 1, 
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      }

The HTML body and form contain calls to two map functions, addMarkers() and zoomout(). 

  <body onload="initialize()">
    Add a list of cities in the text box, one per line:
    <form action="#">
      <textarea rows="4" cols="50" id="cityList">Chicago
Taipei
Curitiba</textarea><br>
      <input type="button" value="Clear text" onclick="document.getElementById('cityList').value=''">
      <input type="button" value="Add markers" onclick="addMarkers(document.getElementById('cityList').value)">
      <input type="button" value="Zoom out" onclick="zoomout()">
    </form>
    <div id="map_canvas" style="width:500px; height:300px"></div>
  </body>


zoomout() is straightforward, and uses the global variable mapCenter:

      function zoomout() {
        map.setZoom(1);
        map.setCenter(mapCenter);
      }

The core function, addMarkers, does two things:
  • add markers for each location given by the user, line by line
  • set up mouse click event listeners for each marker to center the map to itself and zoom in
      function addMarkers(cityList) {
        var cities = cityList.split('\n');


        for (var i = 0; i < cities.length; i++) {
          geocoder.geocode(
            { address: cities[i] },
            function(results, status) {
              var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
              })


             google.maps.event.addListener(marker, 'click',
                function(event) {
                  map.setCenter(event.latLng);
map.setZoom(8);
                });
            }
         );
        }
      }


For each city in our list, we use the geocoder to accept a city name, such as "Sacramento," and convert it to a latitude and longitude that is used to place a marker. The first argument, given in curly braces, is the GeocodeRequest object literal. Passing a (human-readable) address returns a latitude and longitude, and vice-versa. 

Following the request is the function that holds the return value, in our case, the latitude and longitude for each address. Note that we are ignoring the status code here. First, we can place a marker with the geometry.location field, whose type is latLng.

Once a marker is set, an event listener can be added. The first parameter is the object receiving the listener, the second, an event type (found here under "Events" for each class), and the third parameter, the function to be executed when the event is triggered.

No comments:

Post a Comment