Leaflet Ajax JSON file Add to Map as Overlay - json

I have a JSON file that is not formatted in any way to meet geoJson standards. I am trying to load the data I parse from it on the map. I am able to create markers from the data and add them:
$.getJSON( tsdata, function ( data ) {
//loop through all the data
$.each( data.response.docs, function ( key, val ) {
//console.log(val);
if ( typeof val.mc_geo !== 'undefined' ) {
//lat lng isn't consitently 1, so getting the first only.
var geo = val.mc_geo;
var gLat = geo.toString().split( ',' )[ 0 ];
var gLng = geo.toString().split( ',' )[ 1 ];
//add markers to map
var marker = L.marker( [ gLat, gLng ],{icon: tsMarker,} ).bindPopup( "<p><strong><a href='" + val.filename + "'>" + val.title + "</a></strong><hr/><br/><strong>Abstract:</strong> " + truncateString( val.abstract, 350 ) + "</p><p><strong>Author(s): </strong>" + val.author + "<p><strong>Station:</strong> " + val.station_primary_full + "</p>" );
markerArray.push( marker );
}
} );
layer_group = L.layerGroup(markerArray);
map.addLayer(layer_group);
});
This adds the marker layers (layer_group) to the map no problem. However, if I try and add them to the:
L.control.layers(baseMaps, overlayMaps).addTo(map);
I get an error. Basically, L.control.layers is not seeing my layer_group. I can define it before the getJSON call, but L.control.layers will not show the layer full of data though it is "checked" in the layers panel... there are no markers displayed.
How do I dynamically create this marker layer group and have control over it showing (on / off) in my L.control.layers?

It sounds like you add your layer_group to your Layers Control while it is empty ($.getJSON works asynchronously), then re-assign it, so there is no longer a reference between your Layers Control and the markers you have instantiated.
2 easy workarounds:
Add your layer_group to your Layers Control after it is fully built: myLayersControl.addOverlay(layer_group, "Markers")
Use a placeholder Layer Group in your Layers Control, then add your markers into it (myLayerGroup.addLayer(marker)) or simply add your layer_group at the end to it (myLayerGroup.addLayer(layer_group))

Related

How to plot JSON data on mapbox?

I have data in this format:JSON Data
but mapbox is not accepting data in this format. I searched a lot to convert this data into geojson but could not find any better way. How do I plot this type of data on the map? Any suggestions?
Edit:
My question is how do I format this type of data so it will be accepted by mapbox.
This kotlin script queries a datasette API and then plots them on a static mapbox image
https://github.com/yschimke/oksocial/blob/master/commands/london-hospitals
fun staticMap(start: Location, hospitals: List<Location>): String {
var markers = mutableListOf<String>();
markers.add("pin-m-marker+CCC(" + start.longitude + "," + start.latitude + ")");
hospitals.forEach {
markers.add("pin-s-hospital(" + it.longitude + "," + it.latitude + ")");
}
return "https://api.mapbox.com/v4/mapbox.dark/${markers.joinToString(",")}/auto/800x800.png";
}

Output from an array in html page

I am trying to output the contents of an array within an array to a small area on an HTML page. I can only get one dimensional arrays to output.
Simplified, the intended array has a number of properties, but am struggling to find the correct code to output an array nested inside an array.
Properties are;
ID(integer)
Location(string)
Postcode(String)
other properties may be added down the line.
To output the information I am using the following code (which I can only get to work on a single array - even if I change to using [i][x] )
document.write("<tr><td>ID " + i + " is:</td>");
document.write("<td>" + LocationArray[i] + "</td></tr>");
How do I correctly create an array capable of storing the information and then output a specific part of it? eg display the contents of LocationArray[2][3]
Is document.write an efficient method, or is there something better?
I put something together, that could help you. To answer your question at the end about creating an array 'the right way'; There are two possibilities:
Create an array with 'property'-based properties : var locationsArray = [{ID:123,Location:'blabla',Postalcode:'1234'}];
Create an array with string-keys : var locationsArray = [{'ID':123,'Location':'blabla','Postalcode':'1234'}];
In my example I used the first attempt.
To your second question: document.write just writes at the end of the document. If you want to write to a specific area of the website, create a container (for example) and give it an id. Then change the property innerHTML of the created container, as I did in my example.
HTML:
<div id="locations"></div>
<button onclick="printLocations()">Print Locations</button>
Javascript:
function printLocations() {
var locationsArray = [{
ID : 123,
Location : 'Candyland',
Postalcode : '1234'
}, {
ID : 456,
Location : 'Middle-Earth',
Postalcode : '4567'
}
];
var locationsHtml = '';
for (var index in locationsArray) {
locationsHtml += 'ID: ' + locationsArray[index].ID + ', ' +
'Location: ' + locationsArray[index].Location + ', ' +
'Postalcode: ' + locationsArray[index].Postalcode + '<br />';
}
console.log(locationsHtml);
document.getElementById('locations').innerHTML = locationsHtml;
}
If you just want to write a specific part of the array (in your example just one specific location) just use the index you want and access it the same way as in the for loop in my example:
var locationsHtml = locationsArray[1].ID + locationsArray[1].Location + etc...;
/*with string-keys: var locationsHtml = locationsArray[1]['ID'] + etc...;*/
document.getElementById('locations').innerHTML = locationsHtml;

How to get the map zoom action on Ti.map

There are articles about ti.map.
Map
View
I found some entry about zoom.
However I couldn't figure out how to get the map zoom level,
when user pinch the maps on devices.
I tried like this but in vain.
var mapView = Map.createView({
mapType:Map.NORMAL_TYPE,
userLocation:true,
region: {latitude:35.699058, longitude:139.326099,
latitudeDelta:0.01, longitudeDelta:0.01},
animate:false,regionFit:true,
userLocation:true,
});
mapView.addEventListener('pinch', function(evt) {
Ti.API.info("pinch " + evt);
//This is not fired.
});
mapView.addEventListener('click', function(evt) {
Ti.API.info("Clicked " + evt.clicksource + " on " + evt.latitude + "," + evt.longitude);
// This is fired.
});
Thanks to #Fokke Zandbergen's help
I solve the problem.
mapView.addEventListener('regionChanged',function(evt){
Ti.API.info('regionchanged delta lati,longi ' + evt.latitudeDelta + "," + evt.longitudeDelta);
if (evt.latitudeDelta > 0.020){
// do something.
}
});
I think you can achieve your goal by listening to the regionchanged event of the view. You'll get the region displayed, but there's zoom level. Depending on what you need it for you'll have to use the region to calculate that yourself.

Why does Google Maps containsLocation never find a point inside my polygon?

I'm having issues with the following code in that my points never find a point within a polygon using google.maps.geometry.poly.containsLocation. You can see the full code and that there are indeed points in the polygon here http://htinteractive.com/crime_map_fairview.html However in the console you will see that none of the points were found to be in the polygon per the containsLocation function.
I feel like maybe I'm not passing in one the values correctly to the containsLocation function, but so far what I've found in the documentation this seems correct.
var myLatlng = new google.maps.LatLng(lat,lon);
fairview = [
new google.maps.LatLng(39.161536, -86.535107),
new google.maps.LatLng(39.17885, -86.534825),
new google.maps.LatLng(39.179068, -86.547164),
new google.maps.LatLng(39.180989, -86.551803),
new google.maps.LatLng(39.181546, -86.556001),
new google.maps.LatLng(39.170956, -86.569335),
new google.maps.LatLng(39.158487, -86.570365),
new google.maps.LatLng(39.161482, -86.566674),
new google.maps.LatLng(39.157156, -86.559807),
new google.maps.LatLng(39.160084, -86.553961),
new google.maps.LatLng(39.160317, -86.550700),
new google.maps.LatLng(39.160733, -86.548464),
new google.maps.LatLng(39.161482, -86.546172),
new google.maps.LatLng(39.161536, -86.535107)
];
var pv = new google.maps.Polygon(fairview);
if (google.maps.geometry.poly.containsLocation(myLatlng, pv)) {
console.log("Location Found in Polygon!!!!! " + myLatlng.lat() + " " + myLatlng.lng());
} else {
console.log(":( " + myLatlng.lat() + " " + myLatlng.lng());
}
As Dr. Molle pointed out I was instantiating my polygon incorrectly.
var pv = new google.maps.Polygon({path:fairview});

Trouble accessing Array Elements

I'm creating this array.
var GPA_Array:Array=new Array();
var dg:DataGrid= new DataGrid();
gpaBuild();
function gpaBuild()
{
dg.columns=["Num","Course","Grade","Credits"];
GPA_Array.push({Num:"1",Course:"ADS",Grade:"A+",Credits:"4"});
GPA_Array.push({Num:"1",Course:"ADD",Grade:"A+",Credits:"4"});
dg.dataProvider=new DataProvider(GPA_Array);
}
after pushing data in the array ,i need to accees Grade and credits.
I have tried this method,
GPA_Array[0][1],GPA_array[0][2] ,
but it didn't work.
If i try to trace it
trace(GPA_Array[0][1])
it gives me undefined .
also ,when i use trace(GPA_array.toString), it gives me error.
Your push() method appears to be pushing an object into your array, so GPA_Array[0][1] will likely throw an exception. Treating each item in the array as an object and using object notation, you should be able to access it with something like:
Object gpaEntry = GPA_Array[0];
trace("gpaEntry {Num:" + gpaEntry.Num + ",Course:" + gpaEntry.Course + ",Grade:" + gpaEntry.Grade + ",Credits:" + gpaEntry.Credits + "});