Parse JSON and add markers to google map - javascript

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.

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.

How do I get data from all child elements with the same name in Firebase using Javascript?

I'm relatively new to firebase and I want to get the data from all child with the same name (specifically "user, lat, lng") and put in the location in the map. I would also want to know if there is a way to retrieve the data as soon as you add another table.
Here's the JSON:
{
"heartbeat" : {
"-LjiK_rXySmlqlOFdQos" : {
"-LjiK_s6zEovrd_yu8nA" : {
"date" : "Jul-14-2019",
"lat" : 14.6668004,
"lng" : 121.1028933,
"time" : "10:36:06",
"user" : "Test User"
},
"-LjiOGsotaiAGzUpW8L7" : {
"date" : "Jul-14-2019",
"lat" : 14.6668004,
"lng" : 121.1028933,
"time" : "10:52:12",
"user" : "Test User"
},
"-LjiRSK0yM7cbJL1w3lI" : {
"date" : "Jul-14-2019",
"lat" : 14.6668004,
"lng" : 121.1028933,
"time" : "11:06:06",
"user" : "Test User"
},
"-LjiUtQoYJc2_CC4McIp" : {
"date" : "Jul-14-2019",
"lat" : 14.6652018,
"lng" : 121.1060547,
"time" : "11:21:07",
"user" : "Test User"
}
I am using javascript and have tried connecting it to firebase but I can only access the root, not really accomplishing my desired goal.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="map"></div>
<div>
<span>Online users: </span><span id="users">0</span>
</div>
<!-- jQuery CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script>
var config = {
apiKey: "HISNCIHSDNCHINVS",
authDomain: "HISNCIHSDNCHINVS",
databaseURL: "HISNCIHSDNCHINVS",
projectId: "HISNCIHSDNCHINVS",
storageBucket: "HISNCIHSDNCHINVS",
messagingSenderId: "HISNCIHSDNCHINVS",
};
firebase.initializeApp(config);
</script>
<script>
var users_count = 0;
// markers array to store all the markers
var markers = [];
var map;
function initMap() { // google map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(14.5838, 121.0597),
mapTypeId: 'terrain'
});
}
function AddUser(data) {
var icon = { // user icon
/* path: '',*/
scale: 1,
fillColor: "#000",
fillOpacity: 1,
strokeWeight: 1,
anchor: new google.maps.Point(0, 5),
};
var coordinates = { lat: data.val().lat, lng: data.val().lng };
var marker = new google.maps.Marker({
position: coordinates,
icon: icon,
map: map
});
/* --- On click info ---*/
var infowindow = new google.maps.InfoWindow({
content: 'Name: ' + data.val().user + '<br>Latitude: ' + data.val().lat +
'<br>Longitude: ' + data.val().lng
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
markers[data.key] = marker;
document.getElementById("users").innerHTML = users_count;
}
// I want to connect to all my child. Idk what to do.
var users_Ref = firebase.database().ref('/heartbeat');
users_Ref.on('child_added', function (data) {
users_count++;
AddUser(data);
});
users_Ref.on('child_changed', function (data) {
markers[data.key].setMap(null);
AddUser(data);
});
users_Ref.on('child_removed', function (data) {
markers[data.key].setMap(null);
users_count--;
document.getElementById("users").innerHTML = users_count;
});
</script>
https://maps.googleapis.com/maps/api/js?key=INSERT-API-KEY&callback=initMap">
</script>
</body>
The output should be able to put in markers on all the locations based on my firebase. Many thanks for your support!

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>

Creating Markers from my JSON file

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.

Ext Js 4 gmappanel change center dynamically

I've a simple gmappanel (extjs 4.1.1).
How to change the "center" of the map and refresh my window with the center in new coordinate?
My code is:
Ext.Loader.setConfig({
enabled : true
});
Ext.require(['Ext.window.*', 'Ext.ux.GMapPanel']);
Ext.define('AM.view.gmapwindow.GoogleMap', {
extend : 'Ext.window.Window',
alias : 'widget.gmapw',
autoShow : true,
title : 'map',
closeAction : 'hide',
width : 460,
height : 500,
border : false,
x : 40,
y : 60,
items : [{
layout : {
type : 'hbox',
align : 'stretch'
},
flex : 1,
items : [{
xtype : 'textfield'
}, {
xtype : 'button',
handler: function() {
//--------------------
//modify here the center
//geoCodeAddr:'Suisse Romande, Avenue de la Gare, Sion, Svizzera'
//---------------------
}
}]
}, {
width : 450,
layout : 'fit',
height : 450,
border : false,
items : {
xtype : 'gmappanel',
center : {
geoCodeAddr : '4 Yawkey Way, Boston, MA, 02215-3409, USA'
},
markers : []
}
}]
});
the map is well shown, but if i try to change the center editing
geoCodeAddr
with the following code
this.up('gmapw').down('gmappanel').center.geoCodeAddr='Suisse Romande, Avenue de la Gare, Sion, Svizzera';
nothing happens.
any ideas?
Thank you
If you look at GMapPanel.js, you will see that in afterFirstLayout(), geoCodeAddr is used when creating the map. Setting it after layout is not going to do anything since afterFirstLayout() won't be called again.
You should geocode your address and use that to set the center on the map. Something like the following should work:
var map = this.gmap;
var geocoder = new google.maps.Geocoder();
var request = {address: 'Suisse Romande, Avenue de la Gare, Sion, Svizzera'};
var callBack = function(geocoderResults, geocoderStatus) {
if(geocoderStatus === 'OK') {
var location = geocoderResults[0].geometry.location;
var latLng = new google.maps.LatLng(location.lat(), location.lng());
map.setCenter(latLng);
}
}
geocoder.geocode(request,callBack);
I've modify Arun V answer to make it full working for my example.
Thank you again Arun V:
var request = {address: 'Suisse Romande, Avenue de la Gare, Sion, Svizzera'};
var callBack = function(geocoderResults, geocoderStatus) {
if(geocoderStatus === 'OK') {
var location = geocoderResults[0].geometry.location;
var latLng = new google.maps.LatLng(location.lat(), location.lng());
//get current Id from document useful if you have more than one map
//you can't use "this.gmap" reference here because it's not in your scope
var idMapW = this.document.activeElement.id;
Ext.ComponentQuery.query('#'+idMapW)[0].down('gmappanel').gmap.setCenter(latLng);
}
};
this.up('gmapw').down('gmappanel').geocoder.geocode(request,callBack);

Categories

Resources