How would I go about iterating over this JSON data - javascript

I'm pulling in the below json data from a database using ajax.
{"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]}
How would I got about iterating over it to get lat/long pairs to plot on a map?

Assign the JSON data to a variable, and loop through the route object like below:
var j = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]}
for(i=0; i<=j.route.length; i++){
var thisRoute = j.route[i];
}

Give it a try:
var j = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]};
for(var i= 0,len=j.route.length; i<len; i++){
var lat = j.route[i].latitude;
var long = j.route[i].longitude;
console.log(lat+' '+long);
}

var o = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]};
var i = 0;
var lat, long;
var len=o.route.length;
for(i,i<len; i++){
lat = o.route[i].latitude;
long = o.route[i].longitude;
console.log(lat+' '+long);
}

Here's a full implementation of what you're trying to achieve:
JSFIddle with a map
function createMarker(options) {
var marker = new google.maps.Marker(options);
return marker;
}
for (i = 0; i < data.route.length; i++) {
createMarker({
position: new google.maps.LatLng(data.route[i].latitude, data.route[i].longitude),
map: map
});

Related

looped values are not printing in div via javascript

I am trying to print the address and details of my clinics in various locations. However, when i try to do that it is only printing the first element in my div.
Here is my code
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var id = markerNodes[i].getAttribute("id");
var locname = markerNodes[i].getAttribute("locationName");
var locaddress = markerNodes[i].getAttribute("locationAddress1");
var address = markerNodes[i].getAttribute("locationAddress1");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var servicename = markerNodes[i].getAttribute("serviceName");
var clinicfname= markerNodes[i].getAttribute("clinicFname");
var cliniclname= markerNodes[i].getAttribute("clinicLname");
var clinicname= clinicfname + ' ' + cliniclname ;
var clinicAddress= markerNodes[i].getAttribute("clinicAddress");
var clinicCity= markerNodes[i].getAttribute("clinicCity");
var clinicPhone= markerNodes[i].getAttribute("clinicPhone");
var cname= markerNodes[i].getAttribute("cname");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("locationLat")),
parseFloat(markerNodes[i].getAttribute("locationLong")));
document.getElementById('details_name').innerHTML = clinicname;
//console.log (parseFloat(markerNodes[i].getAttribute("locationLong")));
createdetails(clinicname,clinicAddress)
bounds.extend(latlng);
}
In above code am calling a function name createdetails
function createdetails(clinicname,clinicAddress)
{
document.getElementById("details_name").innerHTML=clinicname;
document.getElementById("details_address").innerHTML=clinicAddress;
}
But this div is priniting only first name and first addrees.It have 9 diffrent values for name and address.When i consoled it,it prints.
What is the problem here?
When you are calling document.getElementById("details_name").innerHTML = ..., you are overwriting the current value. Maybe you should append the new name to the existing content with +=:
function createdetails(clinicname,clinicAddress)
{
document.getElementById("details_name").innerHTML+=clinicname;
document.getElementById("details_address").innerHTML+=clinicAddress;
}

Read JSON value Coordinates in JavaScript & Plot to Google Map

I'm trying to Plot google map by getting the coordinates from database.
I've converted the data into JSON & trying to get locations from this JSON.
The JSON is:
[
{"GPS_COORDINATES":"29.392498333333332,71.69455666666666","TOWN":"T00031","LOCALITY":"107","SLOCALITY":"005","STATUS_DATE":"2017-09-16 00:00:00.000","TOTAL_SKU":"0"},
{"GPS_COORDINATES":"29.392564999999998,71.69445666666667","TOWN":"T00031","LOCALITY":"107","SLOCALITY":"005","STATUS_DATE":"2017-09-26 00:00:00.000","TOTAL_SKU":"1"},
{"GPS_COORDINATES":"29.400855,71.66181499999999","TOWN":"T00031","LOCALITY":"107","SLOCALITY":"005","STATUS_DATE":"2017-10-15 00:00:00.000","TOTAL_SKU":"1"}
]
I've tried the following code:
var ltlng = [];
var HiddenValue_gps_Coordinates = document.getElementById("<%=HF_gps_Coordinates.ClientID%>").value;
for (var i = 0; i < HiddenValue_gps_Coordinates.length; i++) {
var obj = HiddenValue_gps_Coordinates[i][0];
//ltlng.push(new google.maps.LatLng(obj.GPS_COORDINATES));
ltlng.push(new google.maps.LatLng(HiddenValue_gps_Coordinates[i][0]));
}
The JSON is set into the HiddenField by using C#
Reference to: JavaScript loop through json array? , I've tried the following code which is showing "undefined" in Console:
var HiddenValue_gps_Coordinates = document.getElementById("<%=HF_gps_Coordinates.ClientID%>").value;
for (var i = 0; i < HiddenValue_gps_Coordinates.length; i++)
{
var obj = HiddenValue_gps_Coordinates[i];
console.log(obj.GPS_COORDINATES);
ltlng.push(new google.maps.LatLng(HiddenValue_gps_Coordinates[i][0]));
}
This is not working for me.
Please Help
UPDATE:
The following code retrieved the coordinates very fine & print them to Console:
var HiddenValue_gps_Coordinates =JSON.parse(document.getElementById("<%=HF_gps_Coordinates.ClientID%>").value);
for (var i = 0; i < HiddenValue_gps_Coordinates.length; i++)
{
var obj = HiddenValue_gps_Coordinates[i];
console.log(obj.GPS_COORDINATES);
//The following is not working
ltlng.push(new google.maps.LatLng(obj.GPS_COORDINATES));
}
This is the snapshot of the Console:
But still I'm unable to plot the markers on Google map by using these Coordinates.
Please Help
You have to tell javascript that it is a JSON object with JSON.parse. Then you can access the properties like you would in code behind.
<script type="text/javascript">
var HiddenValue_gps_Coordinates = JSON.parse(document.getElementById("<%=HF_gps_Coordinates.ClientID%>").value);
for (var i = 0; i < HiddenValue_gps_Coordinates.length; i++) {
ltlng.push(new google.maps.LatLng(HiddenValue_gps_Coordinates[i].GPS_COORDINATES));
}
</script>
Maybe you have to split the coordinates since they are in one property of the json (not tested)
var obj = HiddenValue_gps_Coordinates[i].GPS_COORDINATES.split(",");
ltlng.push(new google.maps.LatLng(obj[0], obj[1]));
UPDATE
Here a complete working example
<asp:HiddenField ID="HF_gps_Coordinates" runat="server" />
<div id="map_canvas" class="map_canvas" style="width: 400px; height: 400px;"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXX&language=nl"></script>
<script type="text/javascript">
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(29.9697393, 71.6469966),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var HiddenValue_gps_Coordinates = JSON.parse(document.getElementById("<%=HF_gps_Coordinates.ClientID%>").value);
for (var i = 0; i < HiddenValue_gps_Coordinates.length; i++) {
var obj = HiddenValue_gps_Coordinates[i].GPS_COORDINATES.split(",");
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(obj[0], obj[1]),
title: 'vdwwd'
});
}
</script>
First, check that the string is displayed correctly doing:console.log(HiddenValue_gps_Coordinates)
That value is a string, not a JavaScript object.
So you need to convert the JSON string into a JavaScript object by doing this:
var myObject = JSON.parse(HiddenValue_gps_Coordinates)
This should work :)

Adding destination lat and lon to destinations variable distancematricx API Success and Fail

I'm trying to get the lat and lon from a Json encoded file for use as destinations for the distance Matrix API rather than add var destinationA = new google.maps.LatLng(??.????, ???.?????); multiple times.
I thought I managed it, as both ways seem to produce the same variable destinations when viewed, yet method two produces an error Uncaught TypeError: a.lat is not a function
This is method one which gives var destination a length of 7:
var destinationA = new google.maps.LatLng(13.7373393, 100.5558883);
var destinationB = new google.maps.LatLng(13.735132, 100.55611199999998);
var destinationC = new google.maps.LatLng(13.736953, 100.55819300000007);
var destinationD = new google.maps.LatLng(13.736244, 100.55694100000005);
var destinationE = new google.maps.LatLng(13.736166, 100.557203);
var destinationF = new google.maps.LatLng(13.738747, 100.55587700000001);
var destinationG = new google.maps.LatLng(13.733558, 100.56020699999999);
var destinations = [destinationA,destinationB,destinationC,destinationD,destinationE,destinationF,destinationG];
works great, will return the distances for each from a given centre point on google map.
Method two:
This is method Two which gives var destination a length of 1, which I am stuck on finding out why its a single length and not 7 as above:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
var first = true;
for (var i=0; i < location_lat_lon.length; i++) {
var sep = first ? '' : ',';
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(lat, lon);
var destinations = [destinations+sep+destination1] ;
first = false;
}
which returns exactly the same result when viewing the variable destinations, yet this returns the error Uncaught TypeError: a.lat is not a function.
Any advice or guidance?
Is it not possible to pass destinations this way to the calculateDistances function?
Thanks in Advance :)
Try this:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
for (var i=0; i < location_lat_lon.length; i++) {
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(parseFloat(lat), parseFloat(lon));
destinations.push(destination1);
}

I'm adding only the last element to the JS array

Here is my code so far: I am trying to create a new JSON object called dataJSON using properties from the GAJSON object. However, when I try to iterate over the GAJSOn object, I get only its last element to be added to the array.
var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":
"3","country":"Spain"},{"bounceRate":"6","country":"Romania"},
{"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"},
{"bounceRate":"2","country":"Norway"}]}';
var GAJSON=JSON.parse(GAstring);
var viewJSON = {
data:[]
};
var dataJSON ={};
for(var i =0; i<GAJSON.data.length; i++) {
dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
dataJSON["country"] = GAJSON.data[i].country;
}
viewJSON.data.push(dataJSON);
Your push of the new object should be within the loop.
for(var i =0; i<GAJSON.data.length; i++) {
viewJSON.data.push({
bounceRate: GAJSON.data[i].bounceRate,
country: GAJSON.data[i].country
});
}
DEMO
You are overwriting values every time at dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
Try this code:
var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":"3","country":"Spain"},{"bounceRate":"6","country":"Romania"}, {"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"}, {"bounceRate":"2","country":"Norway"}]}';
var GAJSON=JSON.parse(GAstring);
var viewJSON = {
data:[]
};
var dataJSON ={};
for(var i =0; i<GAJSON.data.length; i++) {
dataJSON[i] = [];
dataJSON[i]["bounceRate"] = GAJSON.data[i].bounceRate;
dataJSON[i]["country"] = GAJSON.data[i].country;
}
viewJSON.data.push(dataJSON);
console.log(viewJSON);
DEMO

Get Unique values during Loop

I am looping through an array and getting the data that I need.
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
}
What I am trying to do at this point is only show unique data in the loop.
For example var transAccount could be in the array 5 times. I only one to display that in my table once. How can I go about accomplishing this ?
Final Array is constructed like so; just as an object:
finalArray.push({
transID: tmpTrans,
transAccount: tmpAccount,
amEmail: amEmail,
merchName: merchName,
amPhone: amPhone,
amName: amName
});
var allTransAccount = {};
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
if(allTransAccount[finalArray[i].transAccount]) {
var transAccount = '';
}
else {
allTransAccount[transAccount] = true;
}
}
var merhcData = {};
var amName = {};
// and so on
for (var i = 0; i < finalArray.length; i++) {
merchData[finalArray[i].merchName] = finalArray[i].merchName;
amName[finalArray[i].amName] = finalArray[i].amName;
// and so on
}
If you are sure, that data in merchName will never be equal amName or other field - you can use one data object instead of several (merchData, amName...)
What you want is likely a Set. (see zakas for ES6 implementation. To emulate this using javascript, you could use an object with the key as one of your properties (account would be a good bet, as aperl said) which you test before using your raw array.
var theSet={};
for (var i = 0; i < finalArray.length; i++) {
var transAccount = finalArray[i].transAccount;
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
if(!theSet[transAccount]){
//add to your table
theSet[transAccount]===true;
}
This will prevent entries of duplicate data.

Categories

Resources