Creating Markers from my JSON file - javascript

I am creating a map with markers from a json file, my issue is that I am unable to get the markers to show on the map. I can link a basic json file, but when I try with an array file I get no markers. My code is:
<script src="js/mapping.js"></script>
<script type="text/javascript">
(function () {
window.onload = function () {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center : new google.maps.LatLng(51.50746, -0.127594),
zoom : 8,
mapTypeId : google.maps.MapTypeId.ROADMAP
});
// Creating a global infoBox object that will be reused by all markers
infoBubble = new InfoBubble({
minWidth: 300,
maxWidth: 400,
minHeight: 300,
maxHeight: 400,
arrowSize: 50,
arrowPosition: 50,
arrowStyle: 2,
borderRadius: 0,
shadowStyle: 1,
}); // end Creating a global infoBox object
// Creating a global infoBox object tabs
infoBubble.addTab('Details');
infoBubble.addTab('Info');
// end Creating a global infoBox object tabs
// Custom Markers
var markers = {};
var categoryIcons = {
1 : "images/liver_marker1.png",
2 : "images/liver_marker2.png",
3 : "images/liver_marker3.png",
4 : "images/liver_marker4.png",
5 : "images/liver_marker.png",
6 : "images/liver_marker6.png",
7 : "images/liver_marker.png"
} // end Custom Markers
// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position : latLng,
map : map,
title : data.title,
icon : categoryIcons[data.category]
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, 'click', function(e) {
//infoBubble.setContent('<b>'+data.description+'</b>'+'<br>'+data.name);
infoBubble.updateTab(0, 'Details', data.deviceOwnerName);
infoBubble.updateTab(1, 'Info', data.name);
infoBubble.open(map, marker);
map.panTo(loc);
}); // end Attaching a click event to the current marker
})(marker, data); // end Creating a closure
} // end Looping through the JSON data
}
})();
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And my json array file is:
{
"Device" : [{
"DeviceId" : "e889",
"DeviceRef" : "Te889",
"DeviceName" : null,
"DeviceText" : "Operated by SE",
"DeviceLocation" : {
"Latitude" : "51.484804",
"Longitude" : "-0.103226",
"Address" : {
"SubBuildingName" : null,
"BuildingName" : null,
"BuildingNumber" : null,
"Thoroughfare" : null,
"Street" : "Volcan Road North",
"DoubleDependantLocality" : null,
"DependantLocality" : null,
"PostTown" : "Norwich",
"PostCode" : "NR6 6AQ",
"Country" : "gb"
},
"LocationShortDescription" : null,
"LocationLongDescription" : null
},
"Connector" : [{
"ConnectorId" : "JEV01",
"ConnectorType" : "JEVS G 105 (CHAdeMO)",
"RatedOutputkW" : "50.00",
"RatedOutputVoltage" : null,
"RatedOutputCurrent" : null,
"ChargeMethod" : "DC",
"ChargeMode" : "1",
"ChargePointStatus" : "In service",
"TetheredCable" : "0",
"Information" : null
}
],
"Controller" : {
"OrganisationName" : "SE",
"Website" : null,
"TelephoneNo" : null,
"ContactName" : null
},
"DeviceOwner" : {
"OrganisationName" : "Unknown",
"Website" : null,
"TelephoneNo" : null,
"ContactName" : null
},
"DeviceAccess" : {
"RegularOpenings" : [{
"Days" : "Monday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Tuesday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Wednesday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Thursday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Friday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Saturday",
"Hours" : {
"From" : "08:30",
"To" : "05:00"
}
}
],
"Open24Hours" : true
},
"PaymentRequiredFlag" : false,
"SubscriptionRequiredFlag" : true,
"Accessible24Hours" : false,
"PhysicalRestrictionFlag" : false,
"PhysicalRestrictionText" : null,
"OnStreetFlag" : false,
"Bearing" : null
}
]}
I am trying to link to the Latitude and Longitude, but I am also looking to display the DeviceId.
Any help would be appreciated.
R

Latitude and Longitude are nested members within your JSON file. You cannot access them without first delving into the DeviceLocation member. I recommend you read this article (http://www.w3schools.com/json/) to understand how JSON works.

Related

Google maps dragging marker adds border to another marker

I've just tried adding a main draggable marker on to the map. The issue I'm facing is that as soon as you drag that marker in black it creates a blue outline to one of the existing markers that are already placed on the map. I have no idea why it does this. I've isolated the bit of code where it's actually doing this, which is the click event listener that I've added to each marker, as soon as I remove this little snippet of code, it doesn't add a blue outline to any marker anymore. It's important to note, I've also tried commenting out the calls to the two inner function on this click handler however that doesn't seem to fix the issue, so it can't be those functions that are the cause.
It's also not a browser issue as the blue outline appears on both safari and chrome.
marker.addListener('click',
function() {
openCloseNav(true);
car_park_details(marker);
});
You can see the blue outline on the marker here (On the rightmost marker)
Most of the javascript I've added below.
var markers = [];
var geocoder;
var map;
var mainMarker;
function initMap() {
geocoder = new google.maps.Geocoder();
var defaultCoord = {
lat : 51.600960,
lng : -0.275770
};
map = new google.maps.Map(document.getElementById('map'), {
zoom : 15,
center : defaultCoord,
minZoom : 14,
streetViewControl : false,
controlSize : 33,
gestureHandling : 'greedy',
mapTypeControlOptions : {
mapTypeIds : []
},
styles : [ {
"featureType" : "all",
"elementType" : "all",
"stylers" : [ {
"hue" : "#008eff"
} ]
}, {
"featureType" : "road",
"elementType" : "all",
"stylers" : [ {
"saturation" : "0"
}, {
"lightness" : "0"
} ]
}, {
"featureType" : "transit",
"elementType" : "all",
"stylers" : [ {
"visibility" : "off"
} ]
}, {
"featureType" : "water",
"elementType" : "all",
"stylers" : [ {
"visibility" : "simplified"
}, {
"saturation" : "-60"
}, {
"lightness" : "-20"
} ]
} ]
});
mainMarker = new google.maps.Marker({
map,
position: defaultCoord,
draggable: true,
icon : {
url : 'mainmarker.png',
scaledSize : new google.maps.Size(30, 30),
origin : new google.maps.Point(0, 0),
}
});
google.maps.event.addListener(map, 'tilesloaded',
find_closest_markers);
google.maps.event.addListener(mainMarker, 'dragend',
find_closest_markers);
}
function geocodeEncapsulation(i) {
return (function(results, status) {
if (status == 'OK') {
var marker = new MarkerWithLabel({
map : map,
position : results[0].geometry.location,
icon : {
url : 'pin.png',
scaledSize : new google.maps.Size(40, 30),
//origin : new google.maps.Point(0, 0),
},
clickable: true,
labelContent : '£' + i.price.toFixed(2),
labelAnchor : new google.maps.Point(30, 35),
labelClass : "markerdesign",
labelInBackground : false,
title : i.name
});
marker.set("carpark", i);
marker.addListener('mouseover',
function() {
marker.set("labelClass",
"markerdesignhover");
});
marker.addListener('mouseout',
function() {
marker.set("labelClass", "markerdesign");
});
marker.addListener('click',
function() {
openCloseNav(true);
car_park_details(marker);
});
markers.push(marker);
} else {
//console.log(status);
}
});
}
Simplified Version On Fiddle, Drag the centre marker
http://jsfiddle.net/qn23wxmL/2/
Update:
Adding a separate click listener to the draggable marker solves the issue.
However I don't understand how this is working, if anyone can explain, that would be great.

Uncaught TypeError: Cannot read property 'hidden' of undefined(Chart.js)

I'm trying to draw a lineChart and the Errormessage,
Uncaught TypeError: Cannot read property 'hidden' of undefined, occurs and I really don't know what am I missing.
Make canvas with id,'chart'
get the 'JsonObject' from DB using controller
(In the JsonObject, I put the chart type, 'line', and also put the JsonArray, the data)
move the data from JsonArray to Array using function 'getArray' to remove the index
set the chart configuration and make a chart.
function makeChart(year,month,name){
var chart = $('#chart'); //
var valueArray = new Array();
$.ajax({
dataType : 'json',
url : '/individual/makeChart',
data : {
'year': year,
'month': month,
'name' : name
},
async : false,
success : function(json) {
valueArray = getArray(json);
var config = {
type : json.type,
data : {
datasets : [{
borderColor : "#3e95cd",
data : ['1','2','3','4','5','6','7','8','9','10','11','12'],
label : 'region'
}, {
borderColor : "#c45850",
data : ['1','2','3','4','5','6','7','8','9','10','11','12'],
label : 'country'
}],
},
options:{
showLines:true,
legend:{
display:true,
labels:{
fontSize:15,
fontColor:"#000000",
fontStyle:"bold"
}
},
responsive : true,
scales : {
yAxes : [{
ticks : {
beginAtZero : true,
fontSize : 15,
fontColor : "#000000",
fontStyle : "bold"
}
}],
xAxes : [{
ticks : {
fontSize : 15,
fontColor : "#000000",
fontStyle : "bold"
}
}]
}
}
}
new Chart(chart,config); // the problem occurs here!
}
});
}
function getArray(json){
var a = new Array();
a = json.Data[0];
return a;
}

Format GeoJson LineString to Dashed

This is my GeoJson :
{
"type" : "FeatureCollection",
"created" : "2014/07/08 03:00:55 GMT",
"announced_date" : "2017/07/10 03:00:55 GMT",
"features" : [{
"type" : "Feature",
"properties" : {
"name" : "n18",
"analized_date" : "2013/07/08 10:00:00 GMT"
},
"geometry" : {
"type" : "GeometryCollection",
"geometries" : [{
"type" : "Point",
"coordinates" : [134.7, 37.3]
}, {
"type" : "LineString",
"coordinates" : [[134.7, 37.3], [134.6, 37.1]]
}
]
}
}]
}
I can display it in normal line but I want display as dashed line .
I google and there is a way : use Polyline but I don't know how to convert it to Polyline .
Please help . Thank you :) .
To make the poly line dashed, you have to create a native google.maps.Polyline object. One way to do that is to use the data layer to load the GeoJSON, then use its methods to create the polyline from the GeoJSON:
code snippet:
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 8,
center: {
lat: 37,
lng: 134
}
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// process the loaded GeoJSON data.
google.maps.event.addListener(map.data, 'addfeature', function(e) {
if (e.feature.getGeometry().getType() === 'GeometryCollection') {
var geometry = e.feature.getGeometry().getArray();
for (var i = 0; i < geometry.length; i++) {
if (geometry[i].getType() === 'Point') {
map.setCenter(geometry[i].get());
new google.maps.Marker({
map: map,
position: geometry[i].get()
});
} else if (geometry[i].getType() === 'LineString') {
new google.maps.Polyline({
map: map,
path: geometry[i].getArray(),
// make the polyline dashed. From the example in the documentation:
// https://developers.google.com/maps/documentation/javascript/examples/overlay-symbol-dashed
strokeOpacity: 0,
icons: [{
icon: {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
scale: 4
},
offset: '0',
repeat: '20px'
}]
})
}
}
}
map.data.setMap(null);
});
map.data.addGeoJson(data);
}
google.maps.event.addDomListener(window, 'load', initialize);
var data = {
"type" : "FeatureCollection",
"created" : "2014/07/08 03:00:55 GMT",
"announced_date" : "2017/07/10 03:00:55 GMT",
"features" : [{
"type" : "Feature",
"properties" : {
"name" : "n18",
"analized_date" : "2013/07/08 10:00:00 GMT"
},
"geometry" : {
"type" : "GeometryCollection",
"geometries" : [{
"type" : "Point",
"coordinates" : [134.7, 37.3]
}, {
"type" : "LineString",
"coordinates" : [[134.7, 37.3], [134.6, 37.1]]
}
]
}
}]
};
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
width: 100%;
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Parse JSON and add markers to google map

i am trying to parse some JSON data and then transform it into google map markers, but the problem is that I still getting this error:
unexpected non-whitespace character after JSON data
function initialize() {
var myLatlng = new google.maps.LatLng(-35.889050,-64.735108);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var jsonArch = '{ "codigo" : "3127" , "nombre" : "name" , "zona" : "3127" , "geoX" : "-58.443597" , "geoY" : "-34.807164" },{ "codigo" : "3128" , "nombre" : "name" , "zona" : "3128" , "geoX" : "-58.488797" , "geoY" : "-34.576852" },{ "codigo" : "3124" , "nombre" : "name" , "zona" : "3124" , "geoX" : "00.000000" , "geoY" : "00.000000" }';
var archiJASON = jQuery.parseJSON(jsonArch);
/*jQuery.parseJSON(jsonArch, function(json1) {*/
jQuery.each( archiJASON, function(key, data) {
var latLng = new google.maps.LatLng(parseFloat(data.geoX), parseFloat(data.geoY));
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.nombre
});
marker.setMap(map);
});
/*});*/
}
google.maps.event.addDomListener(window, 'load', initialize);
The map is visible, but I could not load markers...
This is JSON data:
'{ "codigo" : "3127" , "nombre" : "name" , "zona" : "3127" , "geoX" : "-58.443597" , "geoY" : "-34.807164" },{ "codigo" : "3128" , "nombre" : "name" , "zona" : "3128" , "geoX" : "-58.488797" , "geoY" : "-34.576852" },{ "codigo" : "3124" , "nombre" : "name" , "zona" : "3124" , "geoX" : "00.000000" , "geoY" : "00.000000" }'
Thank you very much, any help would be appreciated, this really matters me.

I had follow someone code samples and try apply to my HighChart program but I can't get it work at all

I had follow someone code samples, but I'm new to javascript and highcharts. In fact
this program worked but only shows one month at a time, I want show all the months' data. Sorry for my English. Could you give me some advice thanks.
$(document).ready(function () {
var options = {
chart : {
renderTo : 'container',
defaultSeriesType : 'column',
rightMargin : 80
},
title : {
text : 'the scholls'
},
subtitle : {
text : 'data for 2012 years'
},
xAxis : {
title : 'months',
categories : []
},
yAxis : [{
min : 0,
title : {
text : 'students'
}
}, {
linkedTo : 0,
opposite : true
}
],
tooltip : {
formatter : function () {
return '<b>' + this.series.name + '</b><br/>' + this.x + 'Months: ' + this.y + ' students:';
}
},
legend : {
layout : 'vertical',
align : 'right',
verticalAlign : 'top',
x : -10,
y : 100,
borderWidth : 0
},
series : [{
name : "students total",
data : []
}
]
};
//get the json files
$.getJSON('http://localhost:3000/students/givemechart.json', function (data) {
yData = options.series[0].data; //Array to store data for y column
xData = options.xAxis.categories; //Array to store data for x column
xDataObj = data[3]; //only can show one months
yDataObj = data[3]; //only can show one totals
// [[5, 2], [6, 3], [8, 2]]
for (var key in xDataObj) {
xData.push((xDataObj[key].month));
console.dir(xData); //chrome console only
}
for (var key in yDataObj) {
yData.push((yDataObj[key].total));
console.dir(yData); //chrome console only
}
var chart = new Highcharts.Chart(options);
});
});
This is one of my json files.
[
{
"student" : {
"month" : 1,
"total" : 24
}
}, {
"student" : {
"month" : 2,
"total" : 27
}
}, {
"student" : {
"month" : 10,
"total" : 96
}
}, {
"student" : {
"month" : 11,
"total" : 1088
}
}, {
"student" : {
"month" : 12,
"total" : 125
}
}
]
Set Min and Max for Xaxis like this :
xAxis : {
title : 'months',
categories : [],
min: 1,
max: 12
}

Categories

Resources