Google Maps API Tutorial Google Maps API Tutorial
Back to Home Page

Street View Example for Google Maps API

View Example


Notes

Click the marker to see the street view.
The key is to define a loadStreetView function using google.maps.StreetViewService and map.getStreetView:
	function loadStreetView(map, marker) {
		if (marker == undefined || marker == null) return;		
		// Find street view within 200 meters, as street view may not always be available on any latlng
		var service = new google.maps.StreetViewService();
		service.getPanoramaByLocation(marker.getPosition(), 200, function(result, status) {
	        if (status == google.maps.StreetViewStatus.OK) {
	          	var panorama = map.getStreetView();
	    		panorama.setPosition(result.location.latLng);
				panorama.setVisible(true);
	        }
	        else {
	        	alert("No street view is available within " + 200 + " meters");
	        	return;
	        }
	    });
	}


Source Code

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Google Map API V3: Street View</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style type="text/css">
body { margin: 20; padding: 20 }
#map_canvas{
	width: 740px;
	height: 400px;
}
</style>
<script type="text/javascript">
	function loadStreetView(map, marker) {
		if (marker == undefined || marker == null) return;		
		// Find street view within 200 meters, as street view may not always be available on any latlng
		var service = new google.maps.StreetViewService();
		service.getPanoramaByLocation(marker.getPosition(), 200, function(result, status) {
	        if (status == google.maps.StreetViewStatus.OK) {
	          	var panorama = map.getStreetView();
	    		panorama.setPosition(result.location.latLng);
				panorama.setVisible(true);
	        }
	        else {
	        	alert("No street view is available within " + 200 + " meters");
	        	return;
	        }
	    });
	}

    function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(37.286172, -121.80929),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);

        var myLatlng = new google.maps.LatLng(37.286172, -121.80929);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: 'A StreetView Marker'
        });
        google.maps.event.addListener(marker, 'click', function() {
        	loadStreetView(map, marker);
        });
    }
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>