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]))
Related
I am trying to getBounds of dynamically added markers to the map. My goal is to dynamically add markers to a map and have the view automatically zoom to fit the bounds of all the markers on the map. Below is my current code and what I have tried so far:
The starting point is an array of lat & lng:
The web page offers a list of addresses and checkboxes that a user can select and deselect. When the desired addresses are selected the user can click view on map and the makrers will appear on the map (this is working perfectly, I just can't get the view to zoom to the bounds of these markers)
I have a loop that pulls the lat and lng for each checked address and pushes it into an array like this:
latLng.push(42.9570316,-86.04564429999999);
latLng.push(43.009381,-85.890041);
...this is in a loop so it always contains the desired amount of values and outputs this:
latLng = [42.9570316,-86.04564429999999,43.009381,-85.890041,43.11996200000001,-85.42854699999998,43.153376,-85.4730639,42.8976947,-85.88893200000001];
var thisLatLng = L.latLng(latLng);
console.log(thisLatLng); // this returns Null
mymap.fitBounds(group); // returns Error: Bounds are not Valid
mymap.fitBounds(group.getBounds()); // returns group.getBounds() is not a function
I have also tried this as a starting point:
latlng.push(L.marker([42.9570316,-86.04564429999999]));
latlng.push(L.marker([43.009381,-85.890041]));
...this is contained in a loop that results in the output below
latLng = [L.marker([42.9570316,-86.04564429999999]),L.marker([43.009381,-85.890041]),L.marker([43.11996200000001,-85.42854699999998]),L.marker([43.153376,-85.4730639]),L.marker([42.8976947,-85.88893200000001])];
console.log(latLng); // this returns makrers with the correct lat & lng above
var group = new L.featureGroup(latLng);
console.log(group); //this returns a Null featureGroup
mymap.fitBounds(group); // returns Error: Bounds are not valid
mymap.fitBounds(group.getBounds()); // returns Error: Bounds are not valid
I am at a loss on how to make this work I have tried several answers posted on stackoverflow and attempted to try and follow the documentation but nothing seems to give the desired outcome.
Update
I removed latLng.push(L.marker([42.9570316,-86.04564429999999])); loop and replaced with the following:
I created a featuregroup with var group = new L.featureGroup(); then added markers to it in the loop by using marker.addTo(group); this pushed all of the markers into the featuregroup as I would expect but was unable to get bounds.
mymap.fitBounds(group.getBounds()); // returns Error: Bounds are not valid
here is what console.log(group); outputs:
I don't think at all that
latLng = [L.marker([42.9570316,-86.04564429999999]),L.marker([43.009381,-85.890041]),L.marker([43.11996200000001,-85.42854699999998]),L.marker([43.153376,-85.4730639]),L.marker([42.8976947,-85.88893200000001])];
Can work. In leaflet you can't just create a variable and say that it's a marker object. You need to use method like L.marker()
What you need to do is create a single marker and add it to a featureGroup
var group = new L.featureGroup();
for (var i = 0; i < yourMarkers.length; i++) {
L.marker([51.5, -0.09]).addTo(group);
}
map.fitBounds(group.getBounds());
group will now contains multiple markers.
And you can also try this :
var coordinates = new Array();
for (var i = 0; i < yourMarkers.length; i++) {
var marker = L.marker([51.5, -0.09]);
coordinates.push(marker);
}
var group = new L.featureGroup(coordinates);
map.fitBounds(group.getBounds());
UPDATE
The concerned function was this one :
function showResult(lat, lng) {
var marker = L.marker([lat, lng])
.bindPopup('yourPopup').on("popupopen", onPopupOpen).addTo(group);
map.addLayer(group);
map.fitBounds(group.getBounds());
}
You only need to add the fitBounds() inside it.
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.
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'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.
hello can anyone help me debug little error that my eyes seem to be skipping. error is: unexpected ( error. Are my array syntex correct?
function SourceClusting()
{
// grabbing count
var table = document.getElementById('OSDataCount');
var counter= table.rows[1].children[0].innerHTML
// putting all variable into arrays
var latitude()
var longitude()
var i
var marker =[];
// placing values into arrays
for (i=1;i == counter;i++)
{
longitude[i]=table.rows[i].children[6].innerHTML;
latitude[i]=table.rows[i].children[5].innerHTML;
marker[i]=new GMarker(new GLatLng(longitude[i],latitude[i]));
}
var markerCluster = new MarkerClusterer(map, marker);
}
cheers
The problems are in these lines:
var latitude()
var longitude()
You mean
var latitude;
var longitude;
or possibly
var latitude = [];
var longitude = [];
since you seem to be treating them as arrays.
Quite a few things:
You have to parseInt() the string you get from var counter = ..., as a string can't be used in comparisons with integers the way you'd like.
var latitude = () should be var latitude = [], as it's an array, Don't forget those semicolons!
You usually use a lesser-than sign in a loop, not an equality sign ==.
You can condense the loop by initializing i within it.
Try this new, possibly working code:
function SourceClusting() {
// grabbing count
var table = document.getElementById('OSDataCount');
var counter= parseInt(table.rows[1].children[0].innerHTML, 10);
// putting all variable into arrays
var latitude = [];
var longitude = [];
var marker =[];
// placing values into arrays
for (var i = 0; i < counter; i++)
{
longitude[i]=table.rows[i].children[6].innerHTML;
latitude[i]=table.rows[i].children[5].innerHTML;
marker[i]=new GMarker(new GLatLng(longitude[i],latitude[i]));
}
var markerCluster = new MarkerClusterer(map, marker);
}
var latitude() is nonsense. I suspect you mean var latitude = [];
(With a similar correction for the following line)
If you're trying to instantiate an array, instead of:
var latitude();
it should be:
var latitude = [];
You declare var latitidue(), but that doesn't make anysense. Hence the unexpected '('. Also, missing semi-colon after statement.