Translate

Archives

Google Maps JavaScript API V3 Examples

This post contains a number of examples which use the Google Maps JavaScript V3 APIs. I am going assume that you are quite comfortable with JavaScript programming in general and are somewhat familiar with at least Version 2 of the Google Maps JavaScript APIs.

In May 2010, version 2 of the Google Maps API was deprecated in favour of version 3. At the same time Street View support, based on HTML rather than on Flash as in version 2, was added to version 3. The version 2 APIs will be supported for at least three years but no new features will be added.

There are many significant differences between version 2 and version 3. One of the major changes is that all the G* namespaces were changed to google.maps.*. For example, Gmarker is now google.maps.Marker. Unfortunately, there is no mechanical way to convert code which uses version 2 APIs to use version 3 APIs; the changes are so significant and profuse that manual recoding is required.

If you would like an online introductory tutorial to the version 3 APIs, a good one can be found here. A good book on the subject to add to your technical library is Beginning Google Maps API 3 by Gabriel Svennerberg.

Example 1

This is a very simple example which uses Geocoder to determine the latitude and longitude of a given address string and StreetViewPanorama to display that location in Street View.

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
      <title>Example 1 - Google Map JavaScript v3 APIs</title>
      <style type="text/css">
      #map {
         width: 800px;
         height: 600px;
         float: left;
      }
      </style>
      <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

      <script type="text/javascript">

      function init() {
         var userLocation = 'Ocean Street, Swampscott, MA 01907';
         var userPOV = { heading:120, pitch:0, zoom:1};

         var geocoder = new google.maps.Geocoder();

         geocoder.geocode( {'address': userLocation}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                // var latLng = results[0].geometry.location;
                new google.maps.StreetViewPanorama(document.getElementById("map"), 
                                       { position: results[0].geometry.location, pov: userPOV, visible:true });
            } else {
               alert("Geocode failed. Reason: " + status);
            }
         });
     }

     google.maps.event.addDomListener(window, 'load', init);

    </script>
    </head> 
    <body>
       <div id="map"></div>
    </body>
</html>

This is what you should see:

streetview 1

Example 2

In version 2 of the Google Maps JavaScript APIs there was an easy way to highlight which streets were available in Street View using addOverlay, i.e.

   function toggleOverlay() {
       if (!overlayInstance) {
          overlayInstance = new GStreetviewOverlay();
          map.addOverlay(overlayInstance);
       } else {
          map.removeOverlay(overlayInstance);
          overlayInstance = null;
       }
    }


This method of highlighting streets in not available in version 3. In fact, a lot more code is required to achieve the same functionality. The following example shows how to highlight streets with both Street View support and/or Traffic support.

<DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Example 2 - Google Map JavaScript v2 APIs</title>

    <style type="text/css">
      #map {
         width: 800px;
         height: 600px;
      }
      .hilight {
         font-weight: bold;
      }
      .hilight, .lolight {
         background-color: white;
         height: 18px;
         border-style: solid;
         border-color: black;
         border-width: 2px 1px 1px 2px;
         padding-bottom: 2px;
         font-family: arial, sans-serif;
         font-size: 12px;
      }
    </style>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">

    var map;

    function init() {
       var options = {
           scrollwheel: false,
           scaleControl: false,
           backgroundColor: "black",
           navigationControlOptions: {
               position: google.maps.ControlPosition.RIGHT,
               style: google.maps.NavigationControlStyle.DEFAULT
           },
           mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
           },

       }
       map = new google.maps.Map(document.getElementById("map"), options);
       map.setCenter(new google.maps.LatLng(42.467176,-70.921774));
       map.setZoom(12);
       map.setMapTypeId(google.maps.MapTypeId.ROADMAP);

       // streetview tiles
       var street = new google.maps.ImageMapType({
          getTileUrl: function(coord, zoom) {
             var X = coord.x % (1 << zoom);
             return "http://cbk0.google.com/cbk?output=overlay&zoom=" + zoom + "&x=" + X + "&y=" + coord.y + "&cb_client=api";
          },
          tileSize: new google.maps.Size(256, 256),
          isPng: true
       });
       map.overlayMapTypes.push(null);

       // traffic tiles
       var traffic = new google.maps.ImageMapType({
          getTileUrl: function(coord, zoom) {
             var X = coord.x % (1 << zoom);
             return "http://mt3.google.com/mapstt?zoom=" + zoom + "&x=" + X + "&y=" + coord.y + "&client=api";
          },
          tileSize: new google.maps.Size(256, 256),
          isPng: true
       });
       map.overlayMapTypes.push(null);

       // streetview button
       var sButton = document.createElement("button");
       sButton.innerHTML = "StreetView";
       sButton.style.position = "absolute";
       sButton.style.top = "5px";
       sButton.style.right = "90px";
       sButton.style.zIndex = 10;
       map.getDiv().appendChild(sButton);
       sButton.className = "lolight";
       sButton.onclick = function() {
          if (sButton.className == "hilight") {
              map.overlayMapTypes.setAt(0, null);
              sButton.className = "lolight";
          } else {
              map.overlayMapTypes.setAt(0, street);
              sButton.className = "hilight";
          }
       }

       // traffic button
       var tbutton = document.createElement("button");
       tbutton.innerHTML = "Traffic";
       tbutton.style.position = "absolute";
       tbutton.style.top = "5px";
       tbutton.style.right = "173px";
       tbutton.style.zIndex = 10;
       map.getDiv().appendChild(tbutton);
       tbutton.className = "lolight";
       tbutton.onclick = function() {
          if (tbutton.className == "hilight") {
              map.overlayMapTypes.setAt(1, null);
              tbutton.className = "lolight";
          } else {
              map.overlayMapTypes.setAt(1, traffic);
              tbutton.className = "hilight";
          }
       }
    }

    google.maps.event.addDomListener(window, 'load', init);
    </script>

</head>
<body>
   <div id="map"></div>
</body>
</html>


Here is the default display:

streetview 2

Here is the same display with Traffic highlighting:

streetview 3

Here is the same display with Street View highlighting:

streetview 6

Example 3

This example shows how to combine markers with Street View. Click on any street that is highlighted in yellow, and a new green numbered marker is added and the Street View panorama window moves to the marked location.
In addition as you move the mouse over the map, the current latitude and longitude are displayed.

streetview 5

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Example 3 - Google Map JavaScript v3 APIs</title>

    <style type="text/css">
      #map {
        width: 450px;
        height: 400px;
        float: left;
      }

      #pan {
        width: 450px;
        height: 400px;
        float: left;
      }

      #latlng-control {
        background: #ffc;
        border: 1px solid #676767;
        font-size: 10px;
        font-family: arial, helvetica, sans-serif;
        padding: 2px 4px;
        position: absolute;
      }
    </style>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">

      var map;
      var panorama;
      var markcount=0;
      var sv = new google.maps.StreetViewService();

      function LatLngControl(map) {
        this.ANCHOR_OFFSET_ = new google.maps.Point(8, 8);
        this.node_ = this.createHtmlNode_();

        map.controls[google.maps.ControlPosition.TOP].push(this.node_);

        this.setMap(map);

        // hide control until mouse is over map.
        this.set('visible', false);
      }

      // Extend OverlayView so we can access MapCanvasProjection.
      LatLngControl.prototype = new google.maps.OverlayView();
      LatLngControl.prototype.draw = function() {};

      LatLngControl.prototype.createHtmlNode_ = function() {
        var divNode = document.createElement('div');
        divNode.id = 'latlng-control';
        divNode.index = 100;
        return divNode;
      };

      LatLngControl.prototype.visible_changed = function() {
        this.node_.style.display = this.get('visible') ? '' : 'none';
      };

      // display the LatLng moveover
      LatLngControl.prototype.updatePosition = function(latLng) {
        var projection = this.getProjection();
        var point = projection.fromLatLngToContainerPixel(latLng);

        this.node_.style.left = point.x + this.ANCHOR_OFFSET_.x + 'px';
        this.node_.style.top = point.y + this.ANCHOR_OFFSET_.y + 'px';

        this.node_.innerHTML = [
          latLng.toUrlValue(4)
        ].join('');
      };
      function init() {
        var userLatLng = new google.maps.LatLng(42.467176,-70.921774);

        map = new google.maps.Map(document.getElementById('map'), {
          'zoom': 15,
          'center': userLatLng,
          'mapTypeId': google.maps.MapTypeId.ROADMAP,
          streetViewControl: false
        });

        var marker = new google.maps.Marker({
            position: userLatLng
        });
        marker.setMap(map);

        // create new control to display latitude and longitude
        var latLngControl = new LatLngControl(map);

        google.maps.event.addListener(map, 'mouseover', function(mEvent) {
          latLngControl.set('visible', true);
        });
        google.maps.event.addListener(map, 'mouseout', function(mEvent) {
          latLngControl.set('visible', false);
        });
        google.maps.event.addListener(map, 'mousemove', function(mEvent) {
          latLngControl.updatePosition(mEvent.latLng);
        });

        // create new SV panorama
        var panOptions = {
            position: userLatLng,
            addressControl: false,
            navigationControlOptions: {
                position: google.maps.ControlPosition.TOP_RIGHT,
                style: google.maps.NavigationControlStyle.SMALL
            },
            linksControl: false,
            pov: {
               heading: 120,
               pitch: 0,
               zoom: 2
            }
         };

        panorama = new google.maps.StreetViewPanorama(document.getElementById("pan"), panOptions);
        panorama.setVisible(true);

        google.maps.event.addListener(map, 'click', function(mEvent) {
            sv.getPanoramaByLocation(mEvent.latLng, 50, processSVData);
        });
      }

      function processSVData(data, status) {
        if (status == google.maps.StreetViewStatus.OK) {
          markcount++;

          // get new numbered marker image from Google charts.
          var image = new google.maps.MarkerImage( 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + markcount +'|2ad22a|ffffff',
                     new google.maps.Size(20, 34),
                     new google.maps.Point(0, 0),
                     new google.maps.Point(10, 34))

          var marker = new google.maps.Marker({
              position: data.location.latLng,
              icon: image,
              title: location[0],
              zIndex: location[3],
              map: map
          });

          panorama.setPano(data.location.pano);
          panorama.setPov({
            heading: 120,
            pitch: 0,
            zoom: 2
          });
          panorama.setVisible(true);

          google.maps.event.addListener(marker, 'click', function() {
            var markerPanoID = data.location.pano;

            panorama.setPano(markerPanoID);
            panorama.setPov({
              heading: 120,
              pitch: 0,
              zoom: 2
            });
            panorama.setVisible(true);
          });
        } else {
          alert("Street View data not found for this location.");
        }
      }

      google.maps.event.addDomListener(window, 'load', init);

    </script>
  </head>
  <body>
    <div id="map"></div>
    <div id="pan"></div>
  </body>
</html>

streetview 7

As I have reason to use more of the Google Maps JavaScript V3 APIs in interesting or unusual ways, I will add examples of such use here in this post or in another post – so check back from time to time.
 

8 comments to Google Maps JavaScript API V3 Examples

  • Diana

    hi,

    Do you have any example showing POI (temple or church) in city or country ? I know in API V3 there is something ‘poi.place_of_worship” but I’m newbie to start on this google map. Any help to start with such example will be appreciated.

    Diana

  • Hello!
    We have reference to Example 2.
    Thank you!

  • hi

    Do u have any idea why this code doesnt work on Rational Application Development for websphere Software ??
    I have been tried all examples u post but I had empty page and couldnt render map from link considering it as a broken link !!!

    and I have error with this function
    google.maps.event.addDomListener(window, ‘load’, init);

    thanks in advance

  • Sharry

    Hi there, thanks for the examples. Quick question if I may please, how can I get an event to trigger on mouseover on the panorama streetview please? I have panoramaOptions = {linksControl: false} on page load, but I want the links to be viewable on mouseover rather than pov_changed etc.

    Regards

  • Can you do proper screenshots, please? I don´t want to see your full desktop and wallpaper, just the pay. The screenshots as they are are useless in thumbnail view, one has to click to actually see what is in the map, whereas if you had cut the screenshot to show just the browser window instead of the full desktop, the maps would be readable without clicking each one.

    sheesh…

  • I appreciate, result in I discovered exactly what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye