apneadiving / Google-Maps-for-Rails

Enables easy Google map + overlays creation in Ruby apps
https://apneadiving.github.io/
MIT License
2.26k stars 382 forks source link

Add custom controls to map #160

Closed aaronmase closed 12 years ago

aaronmase commented 12 years ago

Is there a way to add custom controls to the map through this gem?. i.e. as per http://code.google.com/apis/maps/documentation/javascript/controls.html#CustomControls

apneadiving commented 12 years ago

Yes it is, here is an example taken from your ref page:

<%= gmaps4rails(@json) %> 
<% content_for :scripts do -%>
<script type="text/javascript" charset="utf-8">
function HomeControl(controlDiv, map) {
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map.
  controlDiv.style.padding = '5px';

  // Set CSS for the control border.
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to set the map to Home';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('DIV');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = 'Home';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago.
  google.maps.event.addDomListener(controlUI, 'click', function() {
    map.setCenter(chicago)
  });
}

Gmaps.map.callback = function(){
  // Create the DIV to hold the control and call the HomeControl() constructor
  // passing in this DIV.
  var homeControlDiv = document.createElement('DIV');
  // the trick is to get the map object
  // Gmaps.map is the map container including everything, Gmaps.map.map is the google's map object itself (I hate this syntax a bit more everyday but was here to ensure backward compatibility..)
  var homeControl = new HomeControl(homeControlDiv, Gmaps.map.map);

  homeControlDiv.index = 1;
  Gmaps.map.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
};
</script>
<% end %>
aaronmase commented 12 years ago

Thanks for posting the solution. I didn't realise it was that unobtrusive.

apneadiving commented 12 years ago

I don't want to get gem user's blocked :)