Вы находитесь на странице: 1из 9

Google Maps JavaScript API V3 Examples

Google Maps JavaScript API V3


Examples
Finnbarr P. Murphy
(fpm@fpmurphy.com)

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.

ly
In May 2010, version 2 of the Google Maps API was deprecated in favour of version 3. At the same

on
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.

se
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
lu
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
a
here. A good book on the subject to add to your technical library is Beginning Google Maps API 3
nn

by Gabriel Svennerberg.

Example 1
o

This is a very simple example which uses Geocoder to determine the latitude and longitude of a
rs

given address string and StreetViewPanorama to display that location in Street View.
pe

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
r

<title>Example 1 - Google Map JavaScript v3 APIs</title>


<style type="text/css">
Fo

#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: user
POV, visible:true });

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 1/9


Google Maps JavaScript API V3 Examples

} 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:

ly
on
se
a lu
o nn
rs
pe

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.
r
Fo

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.

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 2/9


Google Maps JavaScript API V3 Examples

<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;

ly
border-style: solid;
border-color: black;
border-width: 2px 1px 1px 2px;

on
padding-bottom: 2px;
font-family: arial, sans-serif;
font-size: 12px;
}
</style>

se
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"><
/script>
<script type="text/javascript">
var map;
function init() {
lu
var options = {
scrollwheel: false,
scaleControl: false,
a
backgroundColor: "black",
navigationControlOptions: {
nn

position: google.maps.ControlPosition.RIGHT,
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeControlOptions: {
o

style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
rs

}
map = new google.maps.Map(document.getElementById("map"), options);
map.setCenter(new google.maps.LatLng(42.467176,-70.921774));
pe

map.setZoom(12);
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
// streetview tiles
var street = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
r

var X = coord.x % (1 << zoom);


Fo

return "http://cbk0.google.com/cbk?output=overlay&amp;zoom=" + zoom + "&amp;x


=" + X + "&amp;y=" + coord.y + "&amp;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 + "&amp;x=" + X + "&amp;y="
+ coord.y + "&amp;client=api";
},
tileSize: new google.maps.Size(256, 256),
isPng: true
});
map.overlayMapTypes.push(null);
// streetview button

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 3/9


Google Maps JavaScript API V3 Examples

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";
}

ly
}
// traffic button
var tbutton = document.createElement("button");

on
tbutton.innerHTML = "Traffic";
tbutton.style.position = "absolute";
tbutton.style.top = "5px";
tbutton.style.right = "173px";
tbutton.style.zIndex = 10;

se
map.getDiv().appendChild(tbutton);
tbutton.className = "lolight";
tbutton.onclick = function() {
if (tbutton.className == "hilight") {
map.overlayMapTypes.setAt(1, null);
lu
tbutton.className = "lolight";
} else {
map.overlayMapTypes.setAt(1, traffic);
a
tbutton.className = "hilight";
}
nn

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

</head>
<body>
rs

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

Here is the default display:


r
Fo

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 4/9


Google Maps JavaScript API V3 Examples

ly
on
se
Here is the same display with Traffic highlighting:
a lu
o nn
rs
pe
r
Fo

Here is the same display with Street View highlighting:

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 5/9


Google Maps JavaScript API V3 Examples

ly
on
se
Example 3
lu
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
a
window moves to the marked location.
nn

In addition as you move the mouse over the map, the current latitude and longitude are displayed.
o
rs
pe
r
Fo

<!DOCTYPE html>
<html>
<head>

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 6/9


Google Maps JavaScript API V3 Examples

<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;

ly
font-size: 10px;
font-family: arial, helvetica, sans-serif;
padding: 2px 4px;

on
position: absolute;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"><
/script>

se
<script type="text/javascript">
var map;
var panorama;
var markcount=0;
lu
var sv = new google.maps.StreetViewService();
function LatLngControl(map) {
this.ANCHOR_OFFSET_ = new google.maps.Point(8, 8);
this.node_ = this.createHtmlNode_();
a
map.controls[google.maps.ControlPosition.TOP].push(this.node_);
this.setMap(map);
nn

// hide control until mouse is over map.


this.set('visible', false);
}
// Extend OverlayView so we can access MapCanvasProjection.
o

LatLngControl.prototype = new google.maps.OverlayView();


LatLngControl.prototype.draw = function() {};
rs

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

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

};
Fo

// 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({

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 7/9


Google Maps JavaScript API V3 Examples

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 = {

ly
position: userLatLng,
addressControl: false,
navigationControlOptions: {

on
position: google.maps.ControlPosition.TOP_RIGHT,
style: google.maps.NavigationControlStyle.SMALL
},
linksControl: false,
pov: {

se
heading: 120,
pitch: 0,
zoom: 2
}
};
lu
panorama = new google.maps.StreetViewPanorama(document.getElementById("pan"), panO
ptions);
panorama.setVisible(true);
a
google.maps.event.addListener(map, 'click', function(mEvent) {
sv.getPanoramaByLocation(mEvent.latLng, 50, processSVData);
nn

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

markcount++;
// get new numbered marker image from Google charts.
rs

var image = new google.maps.MarkerImage( 'http://chart.apis.google.com/chart?chs


t=d_map_pin_letter&amp;chld=' + markcount +'|2ad22a|ffffff',
new google.maps.Size(20, 34),
pe

new google.maps.Point(0, 0),


new google.maps.Point(10, 34))
var marker = new google.maps.Marker({
position: data.location.latLng,
icon: image,
r

title: location[0],
Fo

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);

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 8/9


Google Maps JavaScript API V3 Examples

});
} 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>

ly
on
se
a lu
o nn
rs

As I have reason to use more of the Google Maps JavaScript V3 APIs in interesting or unusual
pe

ways, I will add examples of such use here in this post or in another post – so check back from
time to time.
r
Fo

03-04-2011 Copyright 2004-2011 Finnbarr P. Murphy. All rights reserved. 9/9

Вам также может понравиться