Google Maps: Creating a Custom Street View Control

When I upgraded my imGoogleMaps JQuery Plugin, I had to create a custom control button on the Google Map. The Control allows the user to add a Street View Overlay to the map. To create the control, I had to assign a prototype object to the instance of the GControl object.

First I created a variable to hold my GStreetviewOverlay. This is important. I did not create this at first, so when a user clicked on the control, the Street View Overlay would be turned on, but could never be turned off. Because this is a global variable, I gave it a distinct name.

?View Code JAVASCRIPT
var imSVOverlay = null;

Then I created the Javascript object.

?View Code JAVASCRIPT
function imStreetViewControl() {}
 
//subclass the GControl Object
imStreetViewControl.prototype = new GControl();
 
//create and style my button
imStreetViewControl.prototype.initialize = function(imGMapObj) {
  var streetViewBtn = document.createElement("div");
  streetViewBtn.style.textDecoration = "none";
  streetViewBtn.style.color = "#000000";
  streetViewBtn.style.backgroundColor = "white";
  streetViewBtn.style.font = "small Arial";
  streetViewBtn.style.fontSize = "11px";
  streetViewBtn.style.fontWeight = "bold";
  streetViewBtn.style.border = "1px solid black";
  streetViewBtn.style.padding = "2px";
  streetViewBtn.style.marginBottom = "3px";
  streetViewBtn.style.textAlign = "center";
  streetViewBtn.style.width = "6em";
  streetViewBtn.style.cursor = "pointer";
  //container.appendChild(streetViewBtn);
  streetViewBtn.appendChild(document.createTextNode("Street view"));
  GEvent.addDomListener(streetViewBtn, "click", function() {
        //if imSVOverlay is null, add the overlay, 
        //else remove the overlay and set the variable back to null  
  	if (!imSVOverlay) {
		imSVOverlay = new GStreetviewOverlay();
		imGMapObj.addOverlay(imSVOverlay);
	} else {
		imGMapObj.removeOverlay(imSVOverlay);
		imSVOverlay = null;
	}	
  });
 
  imGMapObj.getContainer().appendChild(streetViewBtn);
  return streetViewBtn;
}
 
// I want the button to appear on the top right next to the Map, Satellite,
// and Terrain control buttons. 210 pads the button 210 pixels from the right
imStreetViewControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(210, 7));
}

Now I want to add the imStreetViewControl to the map.

?View Code JAVASCRIPT
if (GBrowserIsCompatible()) {
     map = new GMap2(document.getElementById('map'));
     map.setUIToDefault();
     map.addControl(new imStreetViewControl());
}

That’s it. The Street View Control will be added to your map. Enjoy

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks