Repository navigation
Javascript goodies
Keep in mind the gem's conventions:
- prior to v1.0.0, only one map could be created. It's properties were accessible through the
Gmaps4Railsnamespace
From v1.0.0:
-
One map object is instantiated per map displayed. All these objects are independant.
-
all javascript map objects are stored in the
Gmapsobject. To access these, simply type:Gmaps.the_map_id. By default, it'sGmaps.map
Gmaps4rails allows you to update your map on the fly.
Check here the valid json format you should provide: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Control-what-I-display
If you want to create a callback called once the map and items are created, include the following code in your view:
<script type="text/javascript" charset="utf-8">
Gmaps.map.callback = function() {
//whatever you want here
}
</script>
If you want to replace the current markers with your new ones:
Gmaps.map.replaceMarkers(your_markers_json_array); //this is a JS function
If you want to add markers to those already displayed (it doesn't check duplicates):
Gmaps.map.addMarkers(your_markers_json_array); //this is a JS function
Notice that you can use all javascript functions written in the js files directly. I hope the files have enough comments to make everything clear.
#Marker Dragging
Marker dragging is a recurrent question.
I can't see now how to code a clever and generic solution.
For now I suggest the following: adding this behavior thanks to the callback function.
I'd do as follows:
<%= gmaps("markers" => {"data" => @json, "options" => { "draggable" => true } } ) %>
<% content_for :scripts do %>
<script type="text/javascript" charset="utf-8">
Gmaps.map.HandleDragend = function(pos) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
alert(responses[0].formatted_address);
} else {
alert('Cannot determine address at this location.');
}
});
};
Gmaps.map.callback = function() {
for (var i = 0; i < this.markers.length; ++i) {
google.maps.event.addListener(Gmaps4Rails.markers[i].serviceObject, 'dragend', function() { Gmaps.map.HandleDragend(this.getPosition()) });
}
};
</script>
<% end %>
Any remark is welcome.
If location of the user is detected, it will be stored in Gmaps.map.userLocation
If attempt to localize the user fails, you can set the behavior of your app by defining the following function Gmaps.map.geolocationFailure(bool).
Here is an example:
Gmaps.map.geolocationFailure= function(browser_support) {
if (browser_support === true)
{ //User refused geolocation
}
else
{ //Geolocation not supported by the user's browser
}
}