I'm looping through to get a load of long/lats from google directions. However, longArr and latArr only ever have one result in at the end, it's as if the var is getting cleared out each time
function showSteps(directionResult) {
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
var myRoute = directionResult.routes[0].legs[0];
var longArr = "";
var latArr = "";
for (var i = 0; i < myRoute.steps.length; i++) {
var Long = myRoute.steps[i].lat_lngs[0].B;
var Lat = myRoute.steps[i].lat_lngs[0].k;
longArr = Long + Long + "|";
latArr = Lat + Lat + "|";
alert(longArr);
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
$('.long').val(longArr);
$('.lat').val(latArr);
}
First you need to declare your arrays as arrays.
var longArr = [];
var latArr = [];
Then you need to append to them
longArr.push(Long + Long);
latArr.push(Lat + Lat);
When writing the array out to string use join
$('.long').val(longArr.join('|'));
$('.lat').val(latArr.join('|');
To concatenate with the existing value of the string you have to concatenate the variable too.
Option 1:
longArr = longArr + Long + Long + "|" ;
latArr = latArr + Lat + Lat + "|";
Option 2:
longArr += Long + Long + "|" ;
latArr += Lat + Lat + "|";
Related
I have a XML file
<lle:Event>
<lle:eventid>ID01</lle:eventid>
<lle:collab>
<lle:name>Jane Doe</lle:name>
<lle:support>Carer</lle:support>
<lle:supportTime>8am - 8pm</lle:supportTime>
<lle:location>
<lle:lat>1.3117216424564617</lle:lat>
<lle:lng>103.8149642944336</lle:lng>
</lle:location>
</lle:collab>
</lle:Event>
<lle:Event>
<lle:eventid>ID02</lle:eventid>
<lle:collab>
<lle:name>Peter Smith</lle:name>
<lle:support>Carer</lle:support>
<lle:supportTime>8am - 8pm</lle:supportTime>
<lle:location>
<lle:lat>1.3772782313341114</lle:lat>
<lle:lng>103.89873504638672</lle:lng>
</lle:location>
</lle:collab>
</lle:Event>
<lle:Event>
...
</lle:Event>
<lle:Event>
<lle:eventid>ID08</lle:eventid>
<lle:collab>
<lle:name>Ang</lle:name>
<lle:support>Doctor</lle:support>
<lle:supportTime>8am - 8pm</lle:supportTime>
<lle:img>avatar.png</lle:img>
<lle:location>
<lle:lat>1.3577459437939223</lle:lat>
<lle:lng>103.84522878271483</lle:lng>
</lle:location>
</lle:collab>
</lle:Event>
Some lle:Event has lle:img element while some don't.
I am trying to differentiate them using javascript in order to use a custom image marker on Google map for those with lle:img element.
var events = xml.documentElement.getElementsByTagName("lle:Event");
console.log(events);
for (var i = 0; i < events.length; i++) {
var name = xml.documentElement.getElementsByTagName("lle:name")[i].textContent;
var support = xml.documentElement.getElementsByTagName("lle:support")[i].textContent;
var supportTime = xml.documentElement.getElementsByTagName("lle:supportTime")[i].textContent;
var lat = xml.documentElement.getElementsByTagName("lle:lat")[i].textContent;
var lng = xml.documentElement.getElementsByTagName("lle:lng")[i].textContent;
latLng = new google.maps.LatLng(lat, lng);
if (events[i].getElementsByTagName("lle:img").length > 0 ) {
var imgPath = xml.documentElement.getElementsByTagName("lle:img")[i].textContent;
console.log(imgPath);
var marker = new google.maps.Marker({
position: latLng,
map,
title: "Name: " + name + "\nSupport: " + support + "\nSupport Time: " + supportTime,
});
} else if (!events[i].getElementsByTagName("lle:img").length > 0) {
var marker = new google.maps.Marker({
position: latLng,
map,
title: "Name: " + name + "\nSupport: " + support + "\nSupport Time: " + supportTime,
});
}
In the above, I check for whether lle:img exist using
events[i].getElementsByTagName("lle:img").length > 0
However when i try to get imgPath with getElementsByTagName("lle:img")[i].textContent with
var imgPath = xml.documentElement.getElementsByTagName("lle:img")[i].textContent;
the console.log results always shows undefined.
Im very sure the the lle:img element is there but somehow it is still returning undefined. Is there anything wrong that im doing here?
This is what you check in your if
events[i].getElementsByTagName("lle:img").length
and this is what you use to set imgPath
xml.documentElement.getElementsByTagName("lle:img")[i].textContent
see the difference?
In particular, i is the index to the event. It makes no sense to use it to index the "lle:img" elements. You presumably have fewer "lle:img" elements than events, so your index is out of range.
Your else condition is also buggy. It probably works because !...length will be true when length is 0, and true > 0, but that's just lucky. You don't need it at all.
try this
if (events[i].getElementsByTagName("lle:img").length > 0 ) {
var imgPath = events[i].getElementsByTagName("lle:img")[0].textContent;
console.log(imgPath);
...
} else {
...
}
better yet, reduce the number of times you parse it and save your found elements:
var images = events[i].getElementsByTagName("lle:img")
if (images.length > 0) {
var imgPath = images[0].textContent
...
}
else {
...
}
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 trying to learn javascript and getting hung up on this. Basically trying to run the loop and only select the values if profile[i] equals another variable named pro.
Here is the code that selects everything.
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var pro="<?php echo $inform['profile']; ?>";
for (var i = 0; i < markers.length; i++) {
var profile = markers[i].getAttribute("profile");
var date = markers[i].getAttribute("date");
var catch1 = markers[i].getAttribute("catch1");
var catch2 = markers[i].getAttribute("catch2");
var catch3 = markers[i].getAttribute("catch3");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latit")),
parseFloat(markers[i].getAttribute("longit")));
var html = "<b>" + date + "</b> <br/>" + catch1 + "<br/>" + catch2 + "<br/>" + catch3;
var marker = new google.maps.Marker({
map: map,
position: point,
});
bindInfoWindow(marker, map, infoWindow, html);
I tried adding
if (profile['i'] = pro)
{
after
var profile = markers[i].getAttribute("profile");
but it still loops through the whole thing.
Any suggestions?
You are assigning instead of comparing. Use == instead.
var profile = markers[i].getAttribute("profile");
if (profile['i'] == pro)
{
var date = markers[i].getAttribute("date");
var catch1 = markers[i].getAttribute("catch1");
}
I have a function which retrieve data from a xml file and then it is supposed to show it in a div. The problem is that I only get the last element of the array. Is there a way to obtain all the elements and populate them into the div?
Here is the function:
function paradascamionesHistorico() {
google.maps.event.addListener(map, 'click', function() {
infowindowMarkerParadas.close();
});
var Boton = document.getElementById('Boton').value;
var textboxImei = document.getElementById('imeiHistorico').value;
var textboxFecha = document.getElementById('fechaInicioHistorico').value;
var textboxFechaFin = document.getElementById('fechaFinHistorico').value;
var textboxDesdeHora = document.getElementById('desdeHoraHistorico').value;
var textboxHastaHora = document.getElementById('hastaHoraHistorico').value;
downloadUrl("paradas.asp?imei="+textboxImei+"&fecha="+textboxFecha+" "+textboxDesdeHora+"&fechaFin="+textboxFechaFin+" "+textboxHastaHora,
function(data) {
var xml = xmlParse(data);
var markersParadas = xml.documentElement.getElementsByTagName("marker");
var position = [];
//var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersParadas.length; i++) {
var lat = parseFloat(markersParadas[i].getAttribute("lat"));
var lng = parseFloat(markersParadas[i].getAttribute("lng"));
var myLatlngParadas = new google.maps.LatLng(lat, lng);
var fechaInicio = markersParadas[i].getAttribute("fechaInicio");
var fechaFinal = markersParadas[i].getAttribute("fechaFinal");
var diferencia = markersParadas[i].getAttribute("diferencia");
//alert(+diferencia);
var datearray = diferencia.split("/");
var newDate = datearray[1] + '/' + datearray[0] + '/' + datearray[2];
var aFecha = new Date(newDate);
var hours = aFecha.getHours();
var minutes = aFecha.getMinutes();
var seconds = aFecha.getSeconds();
var markerParadas = createMarkerParadas(myLatlngParadas, hours, minutes, seconds, fechaInicio, fechaFinal);
myMarkersParadas.push(markerParadas);
var tablaParadas = '<a href="javascript:myclickParadas(' + (myMarkersParadas.length-1) + ')">' + seconds + '<\/a><br>';
document.getElementById("paradasDiv").innerHTML = tablaParadas;
}//finish loop
}); //end download url
}//termina function
function myclickParadas(i) {
google.maps.event.trigger(myMarkersParadas[i], "click");
}
So if anyone knows how to show the rest of the elements of the array I will be very gratefully.
Best regards.
document.getElementById("paradasDiv").innerHTML = tablaParadas;
You are overwriting innerHTML of #paradasDiv on each iteration of your loop.
That's why you only see the last element of the array.
You have to append to it:
document.getElementById("paradasDiv").innerHTML += tablaParadas;
Also, before starting the loop you maybe need to empty it:
document.getElementById("paradasDiv").innerHTML = '';
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.