Create JSON array from HTML5 localstorage items - javascript

I'm using the jquery ui map in my cordova iOS app, and need to encode all my database results (latitudes and longitudes) in JSON. I already set the localstorage element, and know I received the correct response, but I dont know how to encode all the results into a JSON array. I've tried using a for loop, but I must have done it incorrectly because my code then failed. One more thing, I know that the map works, and also that adding markers work, but I used the demo json array. I need to create my own array with my own objects, and dont know how to. Thanks for the help.
MAP.HTML
<script type="text/javascript">
$(document).ready(function() {
$('#map_canvas').gmap().bind('init', function(evt, map) {
$('#map_canvas').gmap('getCurrentPosition', function(position, status) {
if ( status === 'OK' ) {
var clientPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$('#map_canvas').gmap('addMarker', {'position': clientPosition, 'bounds': true});
$('#map_canvas').gmap('addShape', 'Circle', {
'strokeWeight': 0,
'fillColor': "#008595",
'fillOpacity': 0.25,
'center': clientPosition,
'radius': 15,
'clickable': false
});
}
});
});
var name = localStorage.getItem("name");
var lat = localStorage.getItem("lat");
var lon = localStorage.getItem("lon");
var it = localStorage.getItem("it");
alert(lat);
});
</script>

You need to convert your JSON object to string and store the string.
Use JSON.stringify(yourObject) to convert to string and JSON.parse([your Object from localstorage]).
See similar question

Related

How to convert an array of data into an array of Leaflet LatLngs?

I GET all the locations (latitude + longitude) that works good I can print them an work with them one by one but the problem is that I want to add all locations ligne by ligne in waypoints in one function like in the exemple bellow :
for (i in response.data) {
if (response.data.hasOwnProperty(i)) {
console.log( response.data[i].latitude +' , '+ response.data[i].longitude );
}
}
L.Routing.control({
waypoints: [
L.latLng(33.86477205,-5.57643056),
L.latLng(33.86494131,-5.57304561),
L.latLng(33.86425534,-5.57063162),
],
show: false
}).addTo(map);
I want to add all latitudes and longitudes printed by FOR but in one step not one by one , because I think there is no other way to work with this Leaflet method.
This looks like a simple case of Array manipulation in Javascript. Given an array with arbitrary data, you want a second array with instances of L.LatLng.
A straightforward approach is to map() the array, e.g.:
// For every data point in response.data, create a LatLng
var waypoints = response.data.map(function(dataPoint){
// console.log(dataPoint); // It might be useful to inspect these values
return L.latLng(dataPoint.latitude, dataPoint.longitude);
});
// console.log(waypoints); // Uncommenting this should display an Array of LatLngs
L.Routing.control({
waypoints: waypoints,
show: false
}).addTo(map);

Polygon GeoJSON Features Will Load in Console But Will Not Display in Leaflet

GIS data and python are old hat to me but I am very new to web development and geospatial web applications.
I have followed a tutorial and a class that I am taking to get to the below script but I cannot get the resulting geojson object (the polygon layer) to display within leaflet. I can however, log all of the features of the polygon layer to the console. Furthermore, within the console I can clearly see the correct type, properties, and coordinate arrays of the geojson object. I can also clearly see all of the features within the leaflet map object within the console.
Any input would be greatly appreciated. If needed I will be happy to post the getData.php code. I just don't think that is the problem.
var map,
fieldsin = ["campus_nam", "status", "schnumber", "type"],
autocomplete = [];
$(document).ready(initialize);
function initialize(){
map = L.map("mapdiv", {
center: [36.10, -80.25],
zoom: 12
});
var backgroundLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
//adding postgresql layers to map with getData.php
getData(fieldsin);
};
function getData(fieldsin){
$.ajax({
url: "php/getData.php",
data: { table: "public.school_campus", fields: fieldsin },
success: function(data){
mapData(data);
}
})
};
function mapData(data){
//remove existing map layers
map.eachLayer(function(layer){
//if not the tile layer
if (typeof layer._url === "undefined"){
map.removeLayer(layer);
}
})
//create geojson container object
var geojson = {
"type": "FeatureCollection",
"features": []
};
//split data into features
var dataArray = data.split(", ;");
//pop off the last value of the array because it is an empty string.
dataArray.pop();
//build geojson features
dataArray.forEach(function(d){
d = d.split(", "); //split the comma seperated data string up into individual attribute values
var test = d[fieldsin.length].concat("}");
//feature object container
var feature = {
"type": "Feature",
"properties": {}, //properties object container
//"geometry": JSON.parse(d[fieldsin.length]) //parse geometry
"geometry": JSON.parse(d[fieldsin.length]) //parse geometry
};
//bulding properties for properties container above
for (var i=0; i<fieldsin.length; i++){
feature.properties[fieldsin[i]] = d[i];
};
//add feature names to autocomplete list
if ($.inArray(feature.properties.campus_nam, autocomplete) == -1){
autocomplete.push(feature.properties.campus_nam);
};
//console.log(feature.geometry)
geojson.features.push(feature);
//var campusLayer = L.geoJSON(geojson).addTo(map);
var campusLayer = L.geoJSON(geojson, {
style: {
fillColor: "#CC9900",
color: "#66ffff",
weight: 1
},
onEachFeature: function (feature, layer) {
var html = "";
for (prop in feature.properties){
html += prop+": "+feature.properties[prop]+"<br>";
};
layer.bindPopup(html);
}
}).addTo(map);
});
};
Adding a sample of your resulting GeoJSON object would have surely helped in understanding your situation.
However I highly suspect that you have simply inverted the coordinates:
Leaflet expects [latitude, longitude] order
GeoJSON expects [longitude, latitude] order
See also https://macwright.org/lonlat/
Therefore there is a very high chance your Leaflet GeoJSON Layer Group is actually added onto your map, but you would have to zoom out to see your features on a completely different place and distorded.
Looks like you also have not specified the appropriate CRS to your Leaflet map instance, or you need to convert the coordinates from your backend to the Leaflet's default EPSG:3857.
Note that the GeoJSON spec requests WGS84 CRS, which is the same input for EPSG:3857.

Laravel Google Map Markers

I have this code I used to get the location of each order i receive..
var map;
var markers = <?php echo $order ?>; //this should dump a javascript array object which does not need any extra interperting.
//var marks = []; //just incase you want to be able to manipulate this later
function initMap() {
var cent = {lat: {{$orderlat->Latitude }}, lng: {{ $orderlong->Longitude }} };
var map = new google.maps.Map(document.getElementById('mymap'), {
zoom: 15,
center: cent
});
$.each( markers, function( index, value ){
var lokasi = new google.maps.LatLng({{$order[0]->Latitude }}, {{ $order[0]->Longitude }});
var marker = new google.maps.Marker({
position: lokasi,
map: map
});
});
}
For now it can only return 1 marker, because i was using this
var lokasi = new google.maps.LatLng({{$order[0]->Latitude }}, {{ $order[0]->Longitude }});
I understand I need to remove the 0 to get the rest, however i got an error which reads:
Property [Latitude] does not exist on this collection instance.
I also understand that to remove that error, I need to put them in a blade foreach, my question is, how do we insert blade in script tags? If impossible, what can I do? thanks in advance
In the blade you can simple add tag everywhere that you need:
<script>
var app = 'dd';
</script>
this Code can add in for each and you add scripts that is related to Google map
here you can learn more about blade template system: https://laravel.com/docs/5.5/blade#displaying-data
I would suggest you to make an multi dimensional array of lat long and assign to jquery var
var marker_arr = '{{$marker_locations}}'
and at apply for loop on script to place marker on that location.
Hope this helps you.

How to modify content of an array in Javascript

I'm using the Google Maps API to create some zones on a map. I stored the geodata in a database and I get it through Ajax.
Problem is that API wants the data as an object like :
var myHome = { "lat" : "44.767778" , "long" : "-93.2775" };
So I need to put in the array the {"lat" : and "long : ... };
How could I do that ?
Here is what I did with your help. I've got no error but nothing appears on the map. I used the example with BermudaTriangle from the API like a model : https://developers.google.com/maps/documentation/javascript/examples/polygon-autoclose
$.get(
"getZones.php", //Get geodata from database
function(data) {
locZone = data;
var reg=new RegExp("[/]+", "g"); //Separate points of the zone
var tableau=locZone.split(reg);
for (var i=0; i<tableau.length; i++) {
points = new google.maps.LatLng(tableau[i]);
coords.push(points);//Put the coordinates in a tab
}
var zone = new google.maps.Polygon({
paths: coords, //Use the tab like in the example from API
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
zone.setMap(map);
}
);
That's okay I just rewrote the loop :
for (var i=0; i<tableau.length; i++) {
var b=tableau[i].split(","); //Separate lat & lng
points=new google.maps.LatLng(parseFloat(b[0]), parseFloat(b[1])); //Convert data into float type
coords.push(points);
}
Probably the easiest way (without seeing any example code of you) is by putting the values you get via ajax in a new variable. Let's say the object you get is called geoData. geoData should have the 2 values lat and long or however you called them.
Simpliest way would be:
var myHome = {
"lat": geoData.lat,
"long": geoData.long
}
That's it, hope this helps.
You can also create a LatLng object directly through google maps api:
var latlng = new google.maps.LatLng(44.767778, -93.2775);
That returns the object what you need to work with the maps.

Update coordinate of feature in openlayers 3

I have a model in javascript which has latitude and longitude value. I have to find a feature on the map by the ID of the element and update it's location and several other properties. My code looks like this:
function updateCoordinate(item) {
var features = source.getFeatures();
var featureToUpdate;
// find feature by custom property
for(var i=0; i< features.length; i++) {
if (features[i].get('ID') == item.ID) {
featureToUpdate = features[i];
break;
}
}
// get lon, lat from input item
var lon = item.Coordinate.Longitude;
var lat = item.Coordinate.Latitude;
// update geometry (not working)
featureToUpdate.set('Geometry', new ol.geom.Point(getPointFromLongLat(lon, lat)));
// update custom properties (working)
featureToUpdate.set('MapMarkerTitle', item.Title);
// ...
}
function getPointFromLongLat (long, lat) {
return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')
}
Am I doing something wrong? Is there a better way for this? Is there a better way to find feature by custom property?
By custom poperty I mean that the feature is getting initiated like this:
var fea = new ol.Feature({
geometry: new ol.geom.Point(getPointFromLongLat(lon, lat)),
MapMarkerTitle : 'AAA',
// ...
})
source.addFeatures([fea]);
The custom properties are getting updated but the coordinate doesn't seem to update. Will the feature be redrawn after updating position? The label is however redrawn so I think yes.
UPDATE
After some debugging I found out that, I mispelled the 'geometry' property with uppercase.
Actually:
featureToUpdate.set('geometry', new ol.geom.Point(getPointFromLongLat(lon, lat)));
does set the new position and update the location right away. I would still like to know if what I am doing is the good way or there is better. Thanks!
You can simplify it to:
function updateCoordinate(item) {
var featureToUpdate = source.getFeatureById(item.ID);
var coord = getPointFromLongLat(item.Coordinate.Longitude, item.Coordinate.Latitude);
featureToUpdate.getGeometry().setCoordinates(coord);
featureToUpdate.set('MapMarkerTitle', item.Title);
}

Categories

Resources