Show markers on google maps dynamically -Rails 3.2 - ruby-on-rails

i have a working code that shows multiple markers on google map using geocoder such as
#nearbys = Place.near("#{params[:address]}", 5,:order => "distance",:units => :km)
#nearbys.first(5)
and i display the markers using the below code
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map-canvas-guest"), mapOptions);
map.setTilt(45);
// adding Multiple Markers from ruby object
var markers = [
['<%= #nearbys[0].title %>', '<%= #nearbys[0].latitude %>','<%= #nearbys[0].longitude %>'],
['<%= #nearbys[1].title %>', '<%= #nearbys[1].latitude %>','<%= #nearbys[1].longitude %>'],
['<%= #nearbys[2].title %>', '<%= #nearbys[2].latitude %>','<%= #nearbys[2].longitude %>'],
['<%= #nearbys[3].title %>', '<%= #nearbys[3].latitude %>','<%= #nearbys[3].longitude %>']
,
['<%= #nearbys[4].title %>', '<%= #nearbys[4].latitude %>','<%= #nearbys[4].longitude %>']
];
// adding Info Window Content
var infoWindowContent = [
['<div class="info_content" >' +
'<h3><%= #nearbys[0].title %></h3>' +'</br>'+
'<p><%= #nearbys[0].about %></p>' +
'</div>'],
['<div class="info_content">' +
'<h3><%= #nearbys[1].title %></h3>' +
'<p><%= #nearbys[1].about %></p>' +
'</div>'],
['<div class="info_content">' +
'<h3><%= #nearbys[2].title %></h3>' +'</br>'+
'<p><%= #nearbys[2].about %></p>' +
'</div>'],
['<div class="info_content">' +
'<h3><%= #nearbys[3].title %></h3>' +'</br>'+
'<p><%= #nearbys[2].about %>/p>' +
'</div>'],
['<div class="info_content">' +
'<h3><%= #nearbys[4].title %></h3>' +'</br>'+
'<p><%= #nearbys[4].about %></p>' +
'</div>']
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}//initialize ends
BUT the problem is:-what if #nearbys has less than 5 count,then this code fails.SO i have been trying to make it dynamic using jquery arrays but its not working because i think my code is missing something to work it dynamically.
it should be something like this..
var array=<%= #nearbys%>;
var markers=[];
var infowindows=[];
array.each(function(index){
markers.push('<%= #nearbys[0].title %>', '<%= #nearbys[0].latitude %>','<%= #nearbys[0].longitude %>');
infowindows.push('<div class="info_content" >'+'<h3><%= #nearbys[0].title %></h3>' +'</br>'+
'<p><%= #nearbys[0].about %></p>'+'</div>');
})
..SO how i can achieve this........to make this dynamic so that above working code doesnt breaks with the newly added code.

well after struggling with jquery arrays and json ,i was able to find this best solution...this is working in all scenarios and all i need is to handle empty and null conditions,which i already did and its working the way i needed.HOPE THIS HELPS SOMEONE
my controller
def show_nearby_locations
#nearbys = Place.near("#{params[:address]}", 5,:order => "distance",:units => :km)
#nearbys.first(10)
end
in my view file
<%= javascript_tag do%>
window.nearbys= <%=raw #nearbys.to_json %>;
<%end%>
this is my script inside view
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map-canvas-guest"), mapOptions);
map.setTilt(45);
var markers=[];
var infoWindowContent=[];
$.each(nearbys, function(index) {
console.log( data[0][index].latitude,data[0][index].longitude );
markers.push([nearbys[index]['title'], nearbys[index]['latitude'],nearbys[index]['longitude']]);
infoWindowContent.push(['<div class="info_content" >' +
'<h3 style="color: rgb(<%= rand(0..200)%>,<%= rand(0..200)%> ,<%= rand(0..200)%>);">'+nearbys[index]['title']+'</h3>' +'</br>'+
'<p>'+nearbys[index]['about']+'</p>' +
'</div>']);
});
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}//initialize ends

Hello Friends by doing with Google Maps With Rails i have searched the information from google maps site and Gmaps4rails i have done Multiple Markers and Info-window her is the code
My Controller
#users = User.all
#hash = Gmaps4rails.build_markers(#users) do |user, marker|
marker.lat user.latitude
marker.lng user.longitude
marker.infowindow user.title`
end
In My View
window.onload = function () {
var markers = <%=raw #hash.to_json %>;
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}

Related

how to create costume marker icon rails google maps

i am developing google maps project so i want create costume marker icon here my code in javascript
`window.onload = function initmap() {
var markers = <%=raw #json.to_json %>;
var icon = {
url: '/home/amarnath/Project/myCarparking/app/assets/images/001-map.svg',
size: new google.maps.Size(15, 20),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(15/2, 20/2)
};
var infoWindow = new google.maps.InfoWindow({map: map});
var map = new google.maps.Map(document.getElementById("map_places"));
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geolocpoint = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: geolocpoint,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_places"), mapOptions);
var geomark = new google.maps.Marker({
position: geolocpoint,
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Your geolocation',
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
for (i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.marker_title,
icon: '/home/amarnath/Project/myCarparking/app/assets/images/parking_full.png'
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.infowindow);
infoWindow.open(map, marker);
});
})(marker, data);
}
});
}
}`
and i getting error like this
parking_full.png:1 GET http://localhost:3000/home/amarnath/Project/myCarparking/app/assets/images/parking_full.png 404 (Not Found)
Move your icon to /assets/images folder and add following code:
icon: "/assets/parking_full.png"

trigger a marker click

I am using a Fusion Table and the Google Map API and would like to know if I can automatically trigger an event when a marker is placed.
Currently I can click on the map and I get a customized infowindow, but I want to do the same thing but after geocoding and placing a marker... I would like this to happen automatically.
Here is my code so far:
var FusionTableID = '<?php echo get_theme_mod( 'fusion_id' )?>';
var map = null;
var geocoder = null;
var marker = null;
function initialize() {
geocoder = new google.maps.Geocoder();
var local = new google.maps.LatLng(<?php echo get_theme_mod( 'lat-long' )?>);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: local,
zoom: <?php echo get_theme_mod( 'zoom' )?>
});
// forces a refresh to from Fusion Tables
//var and=' geometry does not contain "'+new Date().getTime()+'"';
var layer = new google.maps.FusionTablesLayer({
//suppressInfoWindows: true,
query: {
select: "col2\x3e\x3e0",
from: FusionTableID,
where: ""
},
options: {
styleId: 2,
templateId: 2
},
map: map
});
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(e) {
var point = e.latLng.toUrlValue(6);
var latlngStr = point.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
position: latlng,
map: map
});
console.log(e.row['objectid'].value);
var tname = e.row['name'].value; // name
var targetDist = e.row['description'].value; // description
// poplulate the infowindow
e.infoWindowHtml = "<div class=\"grid-100\"><h2>"+tname+"</h2>"+targetDist+"<hr></div>";
});
}
function showAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
// THIS DOESN'T WORK ****
new google.maps.event.trigger( marker, 'click' );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Thanks geocodezip
It isn't really possible to "trigger" a click on a FusionTablesLayer (you can, but you basically need to replicate the information in the click event, which is painful), you can query the table an create your own infowindow on the marker though

GoogleMaps4Rails not centering first marker

I am trying to open my first marker on my map via the gmaps4rails gem.
Using the sidebar example from their page:
function createSidebarLi(json) {
return ("<li><a>" + json.title + "</a> (" + json.categories + "...)</li>");
};
function bindLiToMarker($li, marker) {
$li.on('click', function () {
handler.getMap().setZoom(14);
marker.setMap(handler.getMap()); //because clusterer removes map property from marker
marker.panTo();
google.maps.event.trigger(marker.getServiceObject(), 'click');
})
};
handler = Gmaps.build('Google');
handler.buildMap({provider: {
mapTypeId: google.maps.MapTypeId.ROADMAP},
internal: {
id: 'map_sidebar'}}, function () {
var json_array = <%= raw #hash.to_json %>;
var markers = handler.addMarkers(json_array);
_.each(json_array, function (json, index) {
json.marker = markers[index];
});
createSidebar(json_array);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
I am bit confused because of their Version switch. Sometimes it's serviceObject, then it's getServiceObject,-...
I thought something like this
marker.infowindow.open(map, marker.serviceObject);
or this
markers[0].getServiceObject()
markers[0].panTo()
should work?
Can someone please help me out????
Many thanks!
do this in the buildMap callback
google.maps.event.trigger(markers[0].getServiceObject(), 'click');

how to use infowindow (google map API) to get back the ID of the selected location

I am displaying a list of locations (that i get through ViewBag for now) on a map and ask the user to choose one of them.
I have populated my infowindows with HTML code by looping through the list of locations.
now when the user clicks on one of the buttons in the infowindow ("Choose this one"), I want to update the view model (Venue) to include Venue.Id = the choosen location and submit back to the controller so update the database. how can I do such a thing ?
thanks a lot for your help.
here is my script code:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<section class="scripts">
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
function Initialize() {
google.maps.visualRefresh = true;
var rabat = new google.maps.LatLng(34.019657, -6.831833);
var mapOptions = {
zoom: 11,
center: rabat,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var list =
#Html.Raw(Json.Encode(((IEnumerable<KayenChiMVC.Models.Venue>)ViewBag.TheVenue).Select(v => new
{
venueId = v.VenueID,
venueName = v.Name,
venueDistrict = v.District,
venueType = v.SurfaceType,
venueLat = v.Latitude,
venueLon = v.Longitude
})
));
var infowindow = new google.maps.InfoWindow();
for(var i=0; i<list.length;i++){
var pos = new google.maps.LatLng(list[i].venueLat, list[i].venueLon);
var html = "<table>" +
"<tr><td>Nom:</td>" + "<td> " + list[i].venueName +" </td> </tr>" +
"<tr><td>Quartier:</td>" + "<td> " + list[i].venueDistrict +" </td> </tr>" +
"<tr><td>Type de surface:</td>" + "<td> " + list[i].venueType +" </td> </tr>" +
"<tr><td></td><td><input type='button' value='Choisir ce terrain' onclick=''/></td></tr>";
createMarker(pos, list[i].venueName, html);
function createMarker(pos,title, html){
var marker = new google.maps.Marker({
'position': pos,
'map': map,
'title': list[i].venueName
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
}
}
</script>
</section>
Add a data-id attribute to your input to hold the venue id.
<input id="myButton" type="button" data-id="123" value="Choose this one" />
and get the data-id attribute in javascript
document.getElementById('myButton').onclick = function() {
console.log(this.getAttribute('data-id')); // will log '123'
};

Ruby on Rails: Adding a local image in a Google Maps marker

I have a page show_map.html.erb that displays a Google Map (currently working great). I want to add an image instead of the pin marker on the map. I have Googled a lot for this question, and found resources such as this question on StackOverflow. However, my current solution doesn't work.
Do I have to upload an image before using it? Moreover, why can't I use images like public/alert.png OR app/asset/images/alert.png? I referred to the Google Maps API documentation too, but I can't understand the examples.
My controller:
def show_map
#location = Location.find(params[:id])
#address = #location.landmark.gsub(","+")+",+"+#location.place.gsub(","+")+",+"+#location.country
p #address
end
My view:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=<my api key>&sensor=true"> type="text/javascript"></script>
<script type="text/javascript">
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2 id="firstHeading" class="firstHeading" ><font color="#FF0000"><%=#location.title%></font></h2>'+
'<div id="bodyContent" >'+
'<p><%=#location.description%></p>'+
'<p><a href="http:www.google.com">'+
'more info</a> (created on <%=(#location.created_at).strftime("%A, %d/%m/%Y")%>)</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
//set the image
//var image = '/assets/images/alert.png';
// Enable the visual refresh
google.maps.visualRefresh = true;
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//var image = "#{Rails.root}/app/assets/images/alert.png";
//code to search the address
//var address = document.getElementById("address").value;
var address='<%= #address.parameterize %>';
//alert(address);
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title:"<%=#location.title%>",
animation: google.maps.Animation.DROP,
visible: true,
draggable: true,
icon: image
});
//animation for marker
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.DROP);
}
}
//commented as show the info ON click on the marker
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
//listener for animation
google.maps.event.addListener(marker, 'click', toggleBounce);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<body onload="initialize()">
<div id="map" align="right" style="min-height: 500px; height: 400px; width: 400px"></div>
</body>
If you're using the gmaps4rails gem and presuming you've added all dependencies and scripts You will will have something very similar to the following in your controller. You would replace "XYZ" and add your own web address.
def index
#XYZs = XYZ.all
#hash = Gmaps4rails.build_markers(#XYZ) do |XYZ, marker|
marker.lat XYZ.latitude
marker.lng XYZ.longitude
marker.infowindow XYZ.artist
marker.picture({
url: "WWW.YourWebAddressHere.com",
width: 32,
height: 32,
})
end
There are live samples and video documentation for the gem that I found quite helpful.

Resources