Failing to load CSV data through Omnivore - javascript

I am trying to load a CSV file, convert it to GeoJSON, add an empty geoJson layer and then adding data to that geoJson layer. Why is it not working?
var locations = 'locations.csv';
var x = omnivore.csv(locations);
var geojsonLayer = L.geoJson().addTo(map);
geojsonLayer.addData(x);

omnivore.csv returns a layer built with the loaded data, not the underlying GeoJSON object.
Try
var geojsonLayer = omnivore.csv(locations);
geojsonLayer.addTo(map);
Or build your layer and pass it to omnivore.csv:
var geojsonLayer = L.geoJson().addTo(map);
omnivore.csv('locations.csv', null, geojsonLayer);
Or ditch omnivore and use csv2geojson to load your data before populating your layer :
var geojsonLayer = L.geoJson().addTo(map);
xhr = new XMLHttpRequest();
xhr.onload = function() {
csv2geojson.csv2geojson(this.responseText, {}, function(err, data) {
geojsonLayer.addData(data);
});
};
xhr.open('GET', 'locations.csv', true);
xhr.send(null);

Related

Calling a .php document in JavaScript using Django Framework

I'm wondering if this is Django URLs issue. I am following [a Google Tutorial][1] to pop down markers showing addresses on a Google Map pulled from a database using php and xml. I have wired up a .php to my PostgreSQL db okay and seem to be able to run the script and show all the addresses and details in the console (I believe this means the XML file is working too).
The Problem
The trouble I am having is on the JavaScript side: I am using downloadURL() function in my .js static file. And pointing the URL parameter to my .php file which is stored in my local directory:
var markerurl = 'testingland/www/xmlpgd.php'
downloadUrl(markerurl, function(data)
However when I test the script on my local development server (http://127.0.0.1:8000/cafe_list) it returns the following error:
http://127.0.0.1:8000/cafe_list/testingland/www/xmlpgd.php 404 (Not Found)
What I have tried
I have tried moving the xmlpgd.php file to different locations including templates, static and elsewhere. I have tried hosting it on Google Cloud (which returns a CORS error). I am at a loss and thinking maybe I need to wire it up to my urls.py file? I am just not sure whether this is the case or how to do this properly.
My Code
Here is my urls.py file:
urlpatterns = [
path('cafe_list/', views.cafes_home, name='cafes_home'),
url('electra/cafe_list/', views.cafe_list.as_view(), name='cafe_list'),
]
Here is my JS Code:
//loads map markers from database
function downloadUrl(url,callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
//get the markers from php file and adds them to map
var markerurl = 'testingland/www/xmlpgd.php';
downloadUrl(markerurl, function(data) {
var xml = parseXml(data);
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('location');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point
[1]: https://developers.google.com/maps/documentation/javascript/mysql-to-maps

Openlayers authorization authentication [duplicate]

some wms or wfs sources require user and password authentication.
for example https://apps.sogelink.fr/maplink/public/wfs?request=GetCapabilities
need Basic authentication.
How can I inject this authentication?
You can provide your own imageLoadFunction to an ImageWMS source.
The default one just takes the URL and inserts it as the src of the img tag:
ol.source.Image.defaultImageLoadFunction = function(image, src) {
image.getImage().src = src;
};
That question was already asked on the OpenLayers GitHub, here is an example from there:
function customLoader(tile, src) {
var client = new XMLHttpRequest();
client.open('GET', src);
client.setRequestHeader('foo', 'bar');
client.onload = function() {
var data = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(this.responseText));
tile.getImage().src = data;
};
client.send();
}
The documentation of OpenLayers is really good. Just find an example that uses features you want and then follow the links to the API docs.The ol.source.Vector doc even includes an example of a loading function for WFS, where you could manipulate the request:
new ol.source.Vector({
format: new ol.format.GeoJSON(),
loader: function(extent, resolution, projection) {
var wfsUrl = 'TODO';
var xhr = new XMLHttpRequest();
// see above example....
}
});

How to have access to a JSON file without declaring a variable reffering to it

I am working on a django project and want to have access in a JSON file in order to do a geolocation process with the data from the JSON to my template.
The JSON resides in project/static/test/data.js
And it has the below data:
var json= {"count":6,"next":null,"previous":null,"results":[{"title":"Name1","date":"2018-10-02","products":"","categories":"","client_id":{"id":500,"client_id":"3000-3333","title":"Name1","lat":"40.2323","lng":"34.232323","address":"address1","address_no":"","region":"region1","tk":"34343","municipality":"municipality1","department":"department1","description":null,"categories":null,"phone":"2323232332"},"pcategory":"","product_team":""},{"title":Name2....
My script in my template resides in project/templates/test/test_template_json.html
And it has the below script:
<script>
// Initialize and add the map
function initMap() {
var map = new google.maps.Map(
document.getElementById('map'), {
zoom:8,
center: new google.maps.LatLng(37.232323,23.72752323239)
});
//json is the whole document and results is the list with the json objects
for (var x in json.results){
var client=json.results[x].client_id;
var location =new google.maps.LatLng(client.lat,client.lng);
var marker=new google.maps.Marker({
position:location,
map:map});
}
}
</script>
If i use the variable: var json={"count":6,"next":null,.... };
in my data.js file for accessing my json i do not have any problem.
But I want not to declare the var json and still be able to access my json in the test_template_json.html file.
In other words how can i access my json if this has the format:
{"count":6,"next":null,"previous":null,"results":[{"title":...
How can I do it? Any ideas?
Finally after a research period I came up to a solution that worked.The below snippets are in Javascript.
Step 1) Define a XMLHttpRequest object and pass into the open() function the path referring to the json.
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
// xobj.open('GET', '/static/test/download2.json', true);
xobj.open('GET', 'path/path..../path', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
Step 2) Parse the response from loadJSON with JSON.parse(response) , so now you have access to the json data through a javascript variable(var actual_JSON).
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
for (var x in actual_JSON){
var client=actual_JSON[x].client_id;
var location =new google.maps.LatLng(client.lat,client.lng);
var marker=new google.maps.Marker({
position:location,
map:map});
}
});
Then you can easily access the data using a for loop.
A useful article on loading a json file can be found here:https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript

How to generate <a> list from published layers in Geoserver?

I am building a webmapping app. I parse the WMS request to have the title of each layer in layers:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8082/geoserver/wms?service=wms&request=GetCapabilities', true);
xhr.onload = function() {
var parser = new ol.format.WMSCapabilities();
var capabilities = parser.read(xhr.responseText);
var layers = capabilities.Capability.Layer.Layer.Title;
};
But then I fail to access to the titles contain in layers:
$.each(layers, function(i)
{
var list = $('</br><a/>')
.text(layers[i])
.appendTo($('div.myDiv'));
});
What did I miss? Thanx for the help.
I think the problem is, that you need the Name of the Layer, not the Title to be able to call it.
So you would parse the capabilities like this:
var layers = capabilities.Capability.Layer.Layer.Name;

Save interaction draw openlayers

Can anybody give me a hint on how can I save the interaction drawings which I draw in openlayers 3? Can I use json for that? Can anybody provide a simple example?
Thanks!
var features = yourLayer.getSource().getFeatures();
var newForm = new ol.format.GeoJSON();
var featColl = newForm.writeFeaturesObject(features);
Then, save it to JSON:
function exportJson(featuresCollection) {
var txtArray = [];
txtArray.push(JSON.stringify(featuresCollection));
// Here I use the saveAs library to export the JSON as *.txt file
var blob = new Blob(txtArray, {type: 'text/json;charset=utf8'});
saveAs(blob, layerName + ".txt")
};
exportJson(featColl);
To load a JSON:
var vectorLayer = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: 'yourFile.json'
})
});

Categories

Resources