I've got this JS at the end of my HAML view:
:javascript
function initMap() {
var map = new google.maps.Map(document.getElementById('leadsMap')),
markers = [],
bounds = new google.maps.LatLngBounds();
- #leads.each do |lead|
- next unless lead.latitude && lead.longitude
var marker = new google.maps.Marker({
position: {lat: #{lead.latitude}, lng: #{lead.longitude}},
map: map
});
markers.push(marker);
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
How can I parse the #leads so that the loop works correctly? As it stands I get a undefined local variable or method 'lead' error.
try
...
%script
- #leads.each do |lead|
- next unless lead.latitude && lead.longitude
var lead_latitude = "#{lead.latitude}";
var lead_longitude = "#{lead.longitude}";
var marker = new google.maps.Marker({
position: {lat: lead_latitude, lng: lead_longitude},
map: map
});
...
I forget if google maps api allows lat and lng in string, but you can convert lead_latitude and lead_longitude to their need (parseInt, parseDouble, etc).
if you still insist putting ruby variable inside js in haml
I'd recommend using gon 59 accomplish this if you really want to have your Ruby variables in JS.
That said, I'd strongly recommend against using script tags since ideally for security reasons you would want to block all script tags, thus preventing most forms of XSS.
Related
I'm trying to integrate Gmaps in my application, drawing front-end using ExtJs 6.0, and I want to show and hide some user position inside the map.
Adding a marker with user position is quite easy (though I get some strange Cannot read property 'getBounds' of undefined, but I think that's not a big deal).
On the other side, removing a marker it's revealing a little bit more complicated than I thought.
I've read some questions on Stack and Google's Documentation on add/remove markers, and I understand that the "right" way to do it is calling
marker.setMap(null);
But I got a strange behaviour: the marker won't disappear and remains on the map.
This is how I add the marker on the map:
addMarker : function(record) {
var me = this;
var map = me.lookupController().lookupReference('map');
var latitude = record.get('latitude');
var longitude = record.get('longitude');
var description = record.get('fullName');
var marker = new google.maps.Marker({
lat: latitude,
lng: longitude,
title : description
});
me.lookupViewModel().get('techniciansMaker').push(marker);
map.addMarker(marker);
}
And this is how I try to remove marker from the map:
removeMarker : function(record){
var me = this;
var markers = me.lookupViewModel().get('techniciansMaker');
for(var i = 0; i < markers.length; i++){
var m = markers[i];
if (markers[i].getTitle() == record.get('fullName')){
markers[i].setMap(null);
Ext.Array.remove(markers, markers[i]);
}
}
}
Also I'm keeping markers in a list to recognize which one I have to delete.
I can't figure out what I'm doing wrong....
EDIT - SOLVED
I figured out by myself that I was pointing to map container and not the map itself.
Calling map.gmap did the trick.
When using Ext.ux.GMapPanel you should not create the marker yourself with new google.maps.Marker(). Instead addMarker will do this and make listeners:{click:...} work on the marker. You pass the config to addMarker which returns a marker object:
markerConfig = {
lat: latitude,
lng: longitude,
title : description
}
marker = mapPanel.addMarker(markerConfig)
// hide the marker
marker.setMap(null)
// show it again
marker.setMap(mapPanel.gmap)
This allows you to remove the marker and gets rid of that TypeError: Cannot read property 'getBounds' of undefined.
I'm writing a code that will plot multiple locations on a map using google's api. The coordinates, name and MMSI number is stored on an XML file and is imported in a javascript.
This is the part of code I'm talking about:
for(i=0; i<x; i++)
{
var locations = [
['MMSI', 50.26835, 50.45563, 1],
['MMSI', 50.29435, 50.44523, 2],
['MMSI', 50.09399, 50.40548, 3]
}
What I would like to do is add i to the end of 'MMSI' and turn it into a variable which is predefined above.
So what is written above the first code is:
var MMSI1 = 163474;
var MMSI2 = 209483;
var MMSI3 = 705245;
etc, etc...
and need the map markers to display those numbers instead of simply MMSI.
But I don't know how to achieve this as the program won't run every time I try it and google's api will only work with quotes, not variables.
I'm pretty sure there is a simple answer to this question and I am sorry for having to ask such a stupid question but I can't seem to find an answer anywhere or figure it out on my own.
Thanks in advance for any help.
Also I'm sorry if I used any terms wrong I'm still learning this language and I don't always know if I'm saying things correctly.
Ok this seems to work, I removed your ajax call to load the XML and pasted the XML in the fiddle itself. Also, I'm not an XML guru so there might be an easier method for the first part.
http://jsfiddle.net/gt8vK/4/
var x= "<Vessels><Ship><MMSI>431000527</MMSI><CALLSIGN>SLBM</CALLSIGN><LATITUDE>35.4150</LATITUDE><LONGITUDE>139.725</LONGITUDE><DESTINATION>JP SGM</DESTINATION></Ship><Ship><MMSI>244660180</MMSI><CALLSIGN>PD8027</CALLSIGN><LATITUDE>52.4066</LATITUDE><LONGITUDE>4.82345</LONGITUDE><DESTINATION>lalallal</DESTINATION></Ship></Vessels>";
var xmlDoc = new DOMParser().parseFromString(x,'text/xml');
var allShips = xmlDoc.getElementsByTagName("Ship");
console.log(xmlDoc.getElementsByTagName("Ship")[0].getElementsByTagName("MMSI")[0].childNodes[0].text)
var ships = [];
for (var i = 0, l = allShips.length; i < l; i++) {
ships.push({
name: 'MMSI' + (i + 1).toString(),
originalName: allShips[i].getElementsByTagName("MMSI")[0].childNodes[0].nodeValue,
latitude: allShips[i].getElementsByTagName("LATITUDE")[0].childNodes[0].nodeValue,
longitude: allShips[i].getElementsByTagName("LONGITUDE")[0].childNodes[0].nodeValue
})
}
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 2 ,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < ships.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(ships[i].latitude, ships[i].longitude),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(ships[i].name);
infowindow.open(map, marker);
}
})(marker, i));
}
Basically I placed all the ships in an object, instead of creating a new variable for each one, this will keep everything cleaner and you can still access each one of them, just use ships['number'] instead of shipNumber.
Despite spending all day searching and trying numerous code methods I am still having problems with trying to center and zoom a google map correctly.
I wonder if someone would be so kind as to point out the obvious as to what Im doing wrong in my code. Everything worked fine in v2 but Im having difficulty updating to v3.
For information
The map is a small part of a much larger php application, and the needed lat & long map parameters have already been obtained by other methods which are used in the main prog and declared as follows:-
var myDestination=new google.maps.LatLng(e_lat,e_long);
var myHome=new google.maps.LatLng(h_lat,h_long);
Everything seems to be working ok aside from the zoom and center.
Problematic Code is as follows:-
function initialize()
{
// set the map properties
var mapProp = {
center:myHome,
zoom:12,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
// set the home marker
var marker_home=new google.maps.Marker({
position:myHome,
icon:'house.png'
});
marker_home.setMap(map);
//set the destination marker
var marker_destination=new google.maps.Marker({
position:myDestination,
icon:'flag_red.png'
});
marker_destination.setMap(map);
//google polyline between the 2 points
var myPolyline = [myDestination,myHome];
var directPath = new google.maps.Polyline({
path:myPolyline,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
directPath.setMap(map);
// Make an array of the LatLng's of the markers you want to show
var LatLngList = array (new google.maps.LatLng (e_lat,e_long), new google.maps.LatLng (h_lat,h_long));
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend (LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds (bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
TIA for any help :)
In your code "array" is not defined. See jsFiddle.
var LatLngList = array (new google.maps.LatLng (e_lat,e_long), new google.maps.LatLng (h_lat,h_long));
You should use
var LatLngList = new Array(new google.maps.LatLng...)
or
var LatLngList = [new google.maps.LatLng...]
I have a problem. I'm sending to JavaScript strings with lat and lng values. Then, in JavaScript I use the split() method, and gets an array with this values. How can I draw all markers? This function doesn't work properly - the markers aren't created on the map. What is wrong?
var lngstring = <%=lngstring %>
var latstring = <%=latstring %>
alert(latstring);
alert(lngstring);
var arraylat = latstring.split("#");
var arraylng = lngstring.split("#");
alert(arraylat.length) // 200
for (var i = 0; i < arraylat.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(arraylat[i],arraylng[i]),
map: map
});
//alert(arraylat[i],arraylng[i]);
}
alert("ready!");
alert(arraylat[2]); // 37.789879
alert(arraylng[2]); // -122.39044200000001
You need to quote <%=lngstring %> and <%=latstring %> to mark them as a string:
var lngstring = "<%=lngstring %>";
var latstring = "<%=latstring %>";
otherwise you will have something like this:
var lngstring = 18.69872650000002#14.971600200000012#15.58599490000006#16.077066699999932;
which is invalid javascript, and Browser can't parse it.
In your code you do not set a map object, it can be set like below, use this before adding your marker.
var mapOptions = {
zoom: 12
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
In HTML
<div id="map_canvas"></div>
Latitude and Longitude values need to be numbers. Call parseFloat() on the strings you are passing in to the LatLng constructor:
change:
position: new google.maps.LatLng(arraylat[i],arraylng[i])
to:
position: new google.maps.LatLng(parseFloat(arraylat[i]),parseFloat(arraylng[i]))
I'm trying to add markers to a google maps by iterating through a list and retrieving some information. I'm using the prototype library. The code is the following:
var point = new Array();
var myMarkerOptions = new Array();
var marker = new Array();
recommendedList.each(function(item){
point[item.location.ID] = new google.maps.LatLng(item.location.lat, item.location.lng);
myMarkerOptions[item.location.ID] = {
position: point[item.location.ID],
map: map
};
marker[item.location.ID] = new google.maps.Marker(myMarkerOption[item.location.ID]);
});
where the recommendedList is a JSON response of the form:
[
{"artist":"artist1","location":{"lat":"50.952226","lng":"5.34832","ID":28}},
{"artist":"artist2","location":{"lat":"52.362287","lng":"4.883965","ID":32}},
...
]
However, this is not working.
I know that the problem is not about the JSON or the google map, because I tried a simpler version with the following code and it worked:
var myLatlng = new google.maps.LatLng(recommendedList[0].location.lat,recommendedList[0].location.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
So the problem must be in the iteration and the hash maps.
Anyone can see the problem? Thanks!
Simple enough to test without the .each
for (var i=0, item; item = recommendedList[i]; i++) {
point[item.location.ID] = new google.maps.LatLng(item.location.lat, item.location.lng);
myMarkerOptions[item.location.ID] = {
position: point[item.location.ID],
map: map
};
marker[item.location.ID] = new google.maps.Marker(myMarkerOption[item.location.ID]);
}
You can also simplify this quite a lot, unless you "need" those other arrays:
for (var i=0, item; item = recommendedList[i]; i++) {
marker[item.location.ID] = new google.maps.Marker({
new google.maps.LatLng(item.location.lat, item.location.lng),
map
});
}
I think it could be the array accessors you're using. What are you doing the point, myMarkerOptions and marker arrays once you're done with them?
Can you try declaring them as
var point = {};
var myMarkerOptions = {};
var marker = {};
That'll let you refer to them as point[item.location.ID] (etc). I think with the item.ID property being a number, JS is trying to set that numeric index of the array, rather than creating a new property in your hash.
Prototype each iterator doesn't support JSON or object data type.