This is the code I have to show the markers on the map:
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
It's working, but I can't zoom to view all markers in the window when I refresh the page.
I tried:
map.fitBounds(coordinates.getBounds());
But it's not working.
Update your code to:
var fg = L.featureGroup();
fg.addTo(map)
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(fg);
}
}
map.fitBounds(fg.getBounds());
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to execute a function that alerts an array but it doesn't work. When I press the Add button, I'm supposed to have an alert containing Lat/lng, but no alert appears.
You can see my working code here: jsfiddle. Press the Add button to see the phenomenon. I call the function f() in line 195 but I don't get anything.
My HTML code:
<div id="info"></div>
<div id="dvMap"></div>
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="wrapper">Paste coordinate data here:
<form onSubmit="javascript:return false;">
<textarea id="Coords" cols="50" rows="25"></textarea>
<div>
<input type="button" id="btnAdd" class="Button" value="Add Markers" onClick="ProcessData()">
<input type="button" id="btnClear" class="Button" value="Clear Map" onClick="Clear()">
</div>
<br>
</form>
</div>
My Javascript code:
var directionsDisplay = [];
var directionsService = [];
var map = null;
var g = [];
var path = new Array();
var routeSegment = 0;
var k = 0;
function inizialise() {
var mapOptions = {
center: new google.maps.LatLng(33.730166863, 130.7446296584),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
document.getElementById("Coords").value = '33.29702, 130.54948000000002' + '\n' + '33.29764, 130.54986000000002' + '\n' + '33.29793, 130.55010000000001' + '\n' + '33.298730000000006, 130.55066000000002' + '\n' + '33.299620000000004, 130.55129000000002'
// calcRoute() ;
}
var MyArray = [];
function Clear() {
//alert(directionsDisplay.length);
MyArray = [];
for (var i = 0; i < directionsDisplay.length; i++) {
directionsDisplay[i].setMap(null);
}
// directionsDisplay = [];
document.getElementById("Coords").value = "";
document.getElementById("Coords").disabled = false;
document.getElementById("btnAdd").disabled = false;
}
function ProcessData() {
var Points = document.getElementById("Coords").value
if (document.getElementById("Coords").value != '') {
var Points = document.getElementById("Coords").value
calcRoute(Points);
}
}
/*
function ProcessData() {
alert('ok');
if (document.getElementById("Coords").value != '') {
var Points = document.getElementById("Coords").value
AddMarkers(Points);
}
}*/
function AddMarkers(data) {
var MyData = data.substr(0, data.length);
MyArray = MyData.split("\n");
//alert(MyArray[2]);
// calcRoute();
t();
}
function calcRoute(data) {
var MyData = data.substr(0, data.length);
MyArray = MyData.split("\n");
var input_msg = MyArray;
var locations = new Array();
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < input_msg.length; i++) {
var tmp_lat_lng = input_msg[i].split(",");
//var s = new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]);
locations.push(new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]));
bounds.extend(locations[locations.length - 1]);
}
/* var mapOptions = {
// center: locations[0],
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
*/
map.fitBounds(bounds);
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
var i = locations.length;
var index = 0;
while (i != 0) {
if (i < 3) {
var tmp_locations = new Array();
for (var j = index; j < locations.length; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = 0;
index = locations.length;
}
if (i >= 3 && i <= 10) {
console.log("before :fun < 10: i value " + i + " index value" + index);
var tmp_locations = new Array();
for (var j = index; j < locations.length; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = 0;
index = locations.length;
console.log("after fun < 10: i value " + i + " index value" + index);
}
if (i >= 10) {
console.log("before :fun > 10: i value " + i + " index value" + index);
var tmp_locations = new Array();
for (var j = index; j < index + 10; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = i - 9;
index = index + 9;
console.log("after fun > 10: i value " + i + " index value" + index);
}
}
}
var coord = new Array();
function drawRouteMap(locations) {
var start, end;
var waypts = [];
for (var k = 0; k < locations.length; k++) {
if (k >= 1 && k <= locations.length - 2) {
waypts.push({
location: locations[k],
stopover: true
});
}
if (k == 0) start = locations[k];
if (k == locations.length - 1) end = locations[k];
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: false,
travelMode: google.maps.TravelMode.DRIVING
};
console.log(request);
directionsService.push(new google.maps.DirectionsService());
var instance = directionsService.length - 1;
directionsDisplay.push(new google.maps.DirectionsRenderer({
preserveViewport: true
}));
directionsDisplay[instance].setMap(map);
directionsService[instance].route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(status);
directionsDisplay[instance].setDirections(response);
var f = response.routes[0];
// var summaryPanel = document.getElementById("directions_panel");
var route = directionsDisplay[instance].getDirections().routes[0];
// var routes = response.routes;
var points = route.overview_path;
//alert(points);
var ul = document.getElementById("directions_panel");
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
// alert(nextSegment[k]);
var li = document.createElement('P');
li.innerHTML = getLatLng(nextSegment[k]);
ul.appendChild(li);
// polyline.getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
coord.push( getLatLng(nextSegment[k]));
f(coord);
}
}
}
} else {
alert("directions response " + status);
}
});
}
function f( r) {
alert(r);
}
function getLatLng(point) {
//alert(MyArray.length);
var lat = point.lat(),
lng = point.lng();
var tmp = MyArray[k].split(",");
// alert( Math.abs(parseFloat(tmp[0]- lat)) )
if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
k++;
// alert(k);
//if(k==MyArray.length) { f('animation'); }
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
} else {
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
}
}
google.maps.event.addDomListener(window, 'load', inizialise);
The problematic code is in line 195: I call f(coord), but the alert doesn't appear. I have defined the f function as such:
function f(r) {
alert(r);
}
You're overwriting f with an object in line 173:
var f = response.routes[0];
So when you try to call f, it's not a function, but an object (try logging typeof f before the call: you will get 'object').
I managed to fix the problem. I edite my function 'getLatLng()' such as :
function getLatLng(point, array) {
//alert(k);
var lat = point.lat(),
lng = point.lng();
var tmp = MyArray[k].split(",");
// alert( Math.abs(parseFloat(tmp[0]- lat)) )
if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
k++;
array.push({
"lat": lat ,
"lng": lng,
"stop":1
});
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
} else {
array.push({
"lat": lat ,
"lng": lng,
"stop":1
});
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
}
}
Now I can acess to the element of my array. Here my code
Sample of JSON data (from the comments):
[{"id":"280","id_vehicle":"VL0847810531","lat":"30.0761","longi":"1.01981","speed":"144","time":"2014-12-03 12:07:23"},{"id":"202","id_vehicle":"VL0645210631","lat":"34.7344","longi":"7.32019","speed":"78","time":"2014-12-03 11:55:44"}]
function updateLocations(jsonData)
{
for (i=0 ;i< jsonData.length; i++) //for all vehicles
{
var id_vehicle = jsonData[i]["id_vehicle"];
var lat = jsonData[i]["lat"];
var lng = jsonData[i]["longi"];
var speed = jsonData[i]["speed"];
var str_time = jsonData[i]["time"];
/************************update list*******************************/
var state_icon, marker_icon, state;
var time = moment(str_time);
var last_10_Min = moment().subtract({minutes: 60 + 10});
if(time.isBefore(last_10_Min)) //if before 10 last minutes
{
state_icon = INACTIVE_IMG;
marker_icon = INACTIVE_VEHICLE;
state = "INACTIVE";
}
else //if befor
{
if(jsonData[i]["speed"] > 10) //if > 2 km/h then running
{
state_icon = RUN_IMG;
marker_icon = RUN_VEHICLE;
state = "RUN";
}
else
{
state_icon = STOP_IMG;
marker_icon = STOP_VEHICLE;
state = "STOP";
}
}
$("#state_img_"+id_vehicle).attr("src", state_icon);
$("#state_img_"+id_vehicle).attr('state',state);
$("#select_"+id_vehicle).attr("disabled" , false ); // enable selection
/************************update location info*******************************/
var locationInfo = new Array();
img = "<img src=" + state_icon + " width='16' height='16' >";
locationInfo.push("Etat : " + state + " " + img + "<br>");
locationInfo.push("Latitude : " + lat + "<br>");
locationInfo.push("Longitude : " + lng + "<br>");
locationInfo.push("Vitess: " + speed + " klm/h<br>");
locationInfo.push("Temps : " + str_time + "<br>");
$("#info_location_" +id_vehicle).html(locationInfo.join(""));
/*****************update vehicles on map *************/
try {
cBox = $("#select_"+id_vehicle);
if(cBox.is(':checked')) //update selected only
{
//get marker index
var id_map = cBox.attr("id_map");
//change title
title = "Latitude: "+ lat + "\nLongitude: " + lng + "\nSpeed: " + speed + "\nTime: " + str_time;
arrayMarker[id_map].setTitle(title); //update title
arrayMarker[id_map].setIcon(marker_icon);
//move marker
arrayMarker[id_map].setPosition( new google.maps.LatLng(parseFloat(lat),parseFloat(lng)) );
}
}catch(error){};
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
my question is why whene this function is executed (updating locations) just fisrt vehicle on map is moved correctly, the ohers are updated (title, icon ...) but do not move?
I noticed that , they move and return to their old location quickly.
Thanks for any suggestion.
finaly i found problem, it was here:
var marker = new MarkerWithLabel({......});
arrayMarker[id_map] = marker; //put marker in arrayMarker at indexMarker position
the bug occur whene i filled my arrayMarker using MarkerWithLabel (3th lib)
whene changed to native google.maps.Marker it work correcly:
var marker = new google.maps.Marker({......});
arrayMarker[id_map] = marker;
I'm using a Google Maps plugin, and I want it to show up on the page load as well as all postbacks. It seems to only work on postbacks though. Any ideas? I have the body onload tag as "body background="#ccccff" onload="initialize()"", but the function is not defined the first time. Why? Here is the code:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
var mostRecentInfo;
function initialize() {
var center = new google.maps.LatLng(0, 0);
var mapOptions = {
center: center,
zoom:1,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var posStr = <%=JSON%>;
if (posStr.toString() != "0") {
var test = posStr.toString().split(',');
var groundstation = <%=groundStation%>;
var dateTimeStr = <%=datetimesStr%>;
var AUStr = <%=auStr%>;
var spaceCraft = <%=spacecraft%>;
var dateTimes = dateTimeStr.toString().split(',');
var auIDs = AUStr.toString().split(',');
var latitude = new Array((test.length / 2));
var longitude = new Array(latitude.length);
var i = 0;
var markerArray = new Array();
for (var j = 0; j < (test.length - 1); j = j + 2) {
latitude[i] = eval(test[j+1]);
longitude[i] = eval(test[j]);
var position = new google.maps.LatLng(latitude[i], longitude[i]);
var marker = new google.maps.Marker({
map:map,
position:position
});
markerArray.push(marker);
i++;
}
var sumLat = 0;
var sumLong = 0;
for (i = 0; i < latitude.length; i++) {
sumLat += latitude[i];
sumLong += longitude[i];
}
var avgLat = sumLat / latitude.length;
var avgLong = sumLong / longitude.length;
center = new google.maps.LatLng(avgLat, avgLong);
map.panTo(center);
var circle;
var contentStr = new Array();
for (i = 0; i < markerArray.length; i++) {
position = markerArray[i].getPosition();
var circOptions = {
strokeColor:"#770000",
strokeOpacity:0.1,
fillColor:"#881111",
fillOpacity:0.4,
map:map,
center:position,
radius:2500000
};
circle = new google.maps.Circle(circOptions);
marker = markerArray[i];
contentStr[i] = '<div id="content">' +
'<b>Spacecraft: </b>' + spaceCraft.toString() + '<br />' +
'<b>Start Time (UTC): </b>' + dateTimes[i].toString() + '<br />' +
'<b>Position: </b>(' + latitude[i].toString() + ', ' + longitude[i].toString() + ')<br />' +
'<b>AU ID: </b>' + auIDs[i] + '<br />' +
'<b>Downlink Station: </b>' + groundstation.toString() + '<br />' +
'</div>';
addListener(map, marker, contentStr[i]);
}
}
}
function addListener(map, marker, content) {
var infowindow = new google.maps.InfoWindow({
content:content
});
google.maps.event.addListener(marker, 'mouseover', function() {
if (mostRecentInfo)
mostRecentInfo.close();
mostRecentInfo = infowindow;
infowindow.open(map, this);
});
}
etc.
It is likely a timing issue with the onload function being called before the initialize function is ready. This is the reason libraries like jQuery have a document.ready function. You can try removing the onload and place a call to initialize() at the bottom of your HTML, just prior to the closing body tag. This will probably work for you.
If you have the option, I'd use a library so you can assure that the function is there and your page is ready. If you haven't tried it, give jQuery a shot.
I have a list of latitude and longitude in database and I want to draw more polyline on google maps.
For example:
var i, j;
var polyline1 = new Array(latt.length);
str = new Array(latt.length);
for (var k = 0; k < latt.length; k++) {
i = latt[k].split(',');
j = longg[k].split(',');
str[k] = 'new GLatLng(' + i[0] + ',' + j[0] + ')' + ',';
for (var count = 1; count < i.length; count++) {
str[k] += 'new GLatLng(' + i[count] + ',' + j[count] + ')' + ',';
}
str[k] = str[k] + 'new GLatLng(' + i[0] + ',' + j[0] + ')';
polyline1[k] = new GPolyline([str[k]], "#ff0000", 6);
map.addOverlay(polyline1[k]);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
}
but I'm getting error
I don't understand the error - I can't see an a anywhere - but you're almost certainly using GPolyline wrong. It wants an array of objects, not a single-element array of a string of JavaScript:
var polyline1 = new Array(latt.length);
str = new Array(latt.length);
for (var k = 0; k < latt.length; k++) {
var i = latt[k].split(',');
var j = longg[k].split(',');
var latlngs = [];
for (var count = 0; count < i.length; count++) {
latlngs.push(new GLatLng(parseFloat(i[count]), parseFloat(j[count])));
}
polyline1[k] = new GPolyline(latlngs, "#ff0000", 6);
map.addOverlay(polyline1[k]);
}
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
I don't know if the parseFloats are actually necessary. You probably want to move the control adds outside the loop too.
Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?