Loading data from Geoserver in Leaflet js - leaflet

I am trying to load data from Geoserver into my website using Leaflet but I get an error "Uncaught SyntaxError: Unexpected token :" with my Url link to my GeoJSON link.
I'm confused about proxy and CORS but I expect this could be the answer but I am hoping for an easier solution. If anyone is able to help me to solve this problem I will be very grateful.
This is the code I am trying to run.
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/leaflet.css" />
<link rel="markers" type="images/marker-icon" href="images/marker-icon.png" />
<script src="js/leaflet.js"></script>
<script src="js/esri-leaflet.js"></script>
<script src='https://code.jquery.com/jquery-1.11.0.min.js'></script>
<script src='https://code.jquery.com/jquery-1.5.min.js'></script>
</head>
<body>
<div id="map" style="width: 600px; height: 400px;"></div>
<script>
var mymap = L.map('map', {
zoomControl:true, maxZoom:28, minZoom:1
}).fitBounds([[51.0269253989,-1.34762355597],[51.1990603009,-0.951310026203]]);
L.esri.basemapLayer('Imagery').addTo(mymap);
//loads the geojson layer
var geojsonLayer = new L.GeoJSON();
function loadGeoJson(data) {
geojson.addGeoJSON(data);
}
var geoJsonUrl = "http://localhost:8080/geoserver/RSAC/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=RSAC:results_clipped_with_growth_small&maxFeatures=50&outputFormat=application%2Fjson";
$.ajax({
type: "GET",
url: geoJsonUrl + '&callback=?',
dataType: 'json',
jsonpCallback: 'loadGeoJson',
success: loadGeoJson,
});
</script>
</body>
</html>

One problem is here:
<script src='https://code.jquery.com/jquery-1.11.0.min.js'></script>
<script src='https://code.jquery.com/jquery-1.5.min.js'></script>
You included jQuery twice, version 1.5 (very old and outdated) after 1.11.0. Simply remove the second jQuery.
In your Javascript jQuery fetches data in JSONP format. However, the Geoserver URL with outputFormat=application/json will send JSON (not JSONP).
To disable the jQuery's JSONP checks you'll have to provide the parameter jsonp: false here:
Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. (source)
$.ajax({
type: "GET",
url: geoJsonUrl,
dataType: 'json',
success: loadGeoJson,
jsonp: false
});
I tested this with a random public Geoserver instance and had no issues with CORS, but your mileage may vary.

Related

HTMX and chart JS

I was wondering if it was possible to issue an htmx get request to an html block containing a chartJS canvas.
I have a piece of html containing a canvas generated with Chart JS that get called with an HTMX get request but I am unable to generate the chart once the get request is complete.
I have put all the dependencies of chart js in the main html but It is not working.
I also tried to put all the dependencies in the html fragment that gets called by the HTMX GET request but it is not working either.
Is it possible?
Here is what I have so far:
Original
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://unpkg.com/htmx.org#1.6.1" integrity="sha384-tvG/2mnCFmGQzYC1Oh3qxQ7CkQ9kMzYjWZSNtrRZygHPDDqottzEJsqS4oUVodhW" crossorigin="anonymous"></script>
<div id="mainAjax" class="slide-in-left-fade-in fade-me-out fade-in">
<button
class=""
hx-get="/data-viz/simple-chart"
hx-target="#mainAjax"
hx-swap="outerHTML swap:0.2s"
hx-select="#mainAjax"
hx-trigger="myEvent from:body">
Get canvas
</button>
</div>
<script>
document.body.addEventListener("myEvent", function(evt) {
alert("trigger is working")
})
</script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs#2.0.8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/1.2.0/chartjs-plugin-zoom.min.js" integrity="sha512-TT0wAMqqtjXVzpc48sI0G84rBP+oTkBZPgeRYIOVRGUdwJsyS3WPipsNh///ay2LJ+onCM23tipnz6EvEy2/UA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>
</html>
and the Canvas Im trying to fetch:
<div id="mainAjax"class="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js" integrity="sha512-TW5s0IT/IppJtu76UbysrBH9Hy/5X41OTAbQuffZFU6lQ1rdcLHzpU5BzVvr/YFykoiMYZVWlr/PX1mDcfM9Qg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<canvas class="my-4 w-100 chartjs-render-monitor" id="myChart" width="1110" height="468" style="display: block; height: 521px; width: 1234px;"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
var config = {
type: 'line',
data: {
labels : ['2005-03-31', '2005-06-30', '2005-09-30', '2005-12-31', '2006-03-31', '2006-06-30', '2006-09-30', '2006-12-31', '2007-03-31', '2007-06-30', '2007-09-30', '2007-12-31', '2008-03-31', '2008-06-30', '2008-09-30', '2008-12-31', '2009-03-31', '2009-06-30', '2009-09-30', '2009-12-31', '2010-03-31', '2010-06-30', '2010-09-30', '2010-12-31', '2011-03-31', '2011-06-30', '2011-09-30', '2011-12-31', '2012-03-31', '2012-06-30', '2012-09-30', '2012-12-31', '2013-03-31', '2013-06-30', '2013-09-30', '2013-12-31', '2014-03-31', '2014-06-30', '2014-09-30', '2014-12-31', '2015-03-31', '2015-06-30', '2015-09-30', '2015-12-31', '2016-03-31', '2016-06-30', '2016-09-30', '2016-12-31', '2017-03-31', '2017-06-30', '2017-09-30', '2017-12-31', '2018-03-31', '2018-06-30', '2018-09-30', '2018-12-31', '2019-03-31', '2019-06-30', '2019-09-30', '2019-12-31', '2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31', '2021-03-31', '2021-06-30', '2021-09-30'],
datasets: [{
label: 'AAPL Revenue',
lineTension: 0,
data: [3243.0, 3520.0, 3678.0, 5749.0, 4359.0, 4370.0, 4837.0, 7115.0, 5264.0, 5410.0, 6789.0, 9608.0, 7512.0, 7464.0, 12907.0, 11880.0, 9084.0, 9734.0, 12207.0, 15683.0, 13499.0, 15700.0, 20343.0, 26741.0, 24667.0, 28571.0, 28270.0, 46333.0, 39186.0, 35023.0, 35966.0, 54512.0, 43603.0, 35323.0, 37472.0, 57594.0, 45646.0, 37432.0, 42123.0, 74599.0, 58010.0, 49605.0, 51501.0, 75872.0, 50557.0, 42358.0, 46852.0, 78351.0, 52896.0, 45408.0, 52579.0, 88293.0, 61137.0, 53265.0, 62900.0, 84310.0, 58015.0, 53809.0, 64040.0, 91819.0, 58313.0, 59685.0, 64698.0, 111439.0, 89584.0, 81434.0, 83360.0],
backgroundColor: '#A3BE8C4D',
fill: false,
showLine : true,
borderColor:
'#A3BE8C'
,
borderWidth: 1
}],
},
}
var myChart = new Chart(ctx, config);
console.log(myChart.data.datasets)
document.body.addEventListener("cart-updated",
function (evt) {
alert("cart updated")
})
</script>
</div>

Editing feature in OpenLayers2 published by geoserver and saving the updated in postgres connected database table

I have published a shapefile "ind_adm2" in geoserver as Postgis(postgres database), It can be accessed as webpage using OpenLayers code given below. Now I need to edit the shapefile on webpage itself and save the edited(updated) things in Postgres database. Can anyone help !!
I tried using wfs URL of geoserver but unable to select the feature.
<html>
<head>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
</head>
<body>
<div style="width:100%; height:100%" id="map"></div>
<script defer="defer" type="text/javascript">
var map = new OpenLayers.Map('map');
basemap = new OpenLayers.Layer.WMS( "Layer Name1",
"http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic'} );
utility = new OpenLayers.Layer.WMS( "Layer Name2",
"http://localhost:8080/geoserver/iirs/ows?", {layers: 'iirs:ind_adm2',
transparent:"true"}, {isBaseLayer:false} );
map.addLayers([basemap,utility]);
map.zoomToMaxExtent();
</script>
</body>
</html>
Its expected to select any polygon then edit there itself and update the edits in postgres database.
As what you need will be much more complex than your existing code you should update that to the latest version of OpenLayers (currently 5.3.0) and develop with that. It is easier to get started using the full build https://openlayers.org/en/latest/doc/quickstart.html which is very similar to using versions 3 and 4 so you will be able to reuse examples from those versions. For help about editing WFS here's one question with links a tutorial and some examples Javascript editing WFS from GeoServer using OpenLayers
<html>
<head>
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
</head>
<body>
<div style="width:100%; height:100%" id="map"></div>
<script defer="defer" type="text/javascript">
var basemap = new ol.layer.Image({
source: new ol.source.ImageWMS({
url: "http://vmap0.tiles.osgeo.org/wms/vmap0",
params: {
'LAYERS': 'basic'
},
projection: 'EPSG:4326',
ratio: 1
})
});
var utility = new ol.layer.Image({
source: new ol.source.ImageWMS({
url: "http://localhost:8080/geoserver/iirs/ows",
params: {
'LAYERS': 'iirs:ind_adm2',
'TRANSPARENT': 'true'
},
projection: 'EPSG:4326'
})
});
var map = new ol.Map({
target: 'map',
layers: [basemap], utility],
view: new ol.View({
projection: 'EPSG:4326'
})
});
map.getView().fit(map.getView().getProjection().getExtent());
</script>
</body>
</html>

How to get uber ride price

I edited the whole topic because I gave a great read about the whole API and now I'm having another problem ... I'll try to leave as much details as possible here.
The error you are giving is 401 of uber api, but, I did everything right ... My INDEX.html looks like this:
index.html
<html>
<head>
<title>Party Invitation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<section>
<h1>Party</h1>
<div class="info-container">
<span class="info-header">When</span>
<span class="info when">September 18, 2014 at 6:00pm</span>
</div>
<div class="info-container">
<span class="info-header">Where</span>
<span class="info where">Thinkful HQ</span>
</div>
<img class="map" src="http://maps.googleapis.com/maps/api/staticmap?center=40.7248,-73.99597&zoom=17&format=png&sensor=false&size=280x280&maptype=roadmap&style=element:geometry.fill|color:0xf4f4f4&markers=color:red|40.7248,-73.99597&scale=2" alt="">
<div class="button">
<p id="time">ESTIMATING TIME</p>
</div>
</section>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/uber.js"></script>
</body>
And then my uber.js is like this:
uber.js
// Uber API Constants
var uberClientId = "RxGbzH***************"
, uberServerToken = "h_hqd3L4***************";
// Create variables to store latitude and longitude
var userLatitude
, userLongitude
, partyLatitude = 19.3256725
, partyLongitude = -43.1579731;
navigator.geolocation.watchPosition(function(position) {
// Update latitude and longitude
userLatitude = position.coords.latitude;
userLongitude = position.coords.longitude;
// Query Uber API if needed
getEstimatesForUserLocation(userLatitude, userLongitude);
});
function getEstimatesForUserLocation(latitude,longitude) {
$.ajax({
url: "https://api.uber.com/v1/estimates/price",
headers: {
Authorization: "KA.ey**********************************************************************************************************************************" + uberServerToken
},
data: {
start_latitude: latitude,
start_longitude: longitude,
end_latitude: partyLatitude,
end_longitude: partyLongitude
},
success: function(result) {
console.log(result);
}
});
}
And this is the error that is appearing
And my uber control panel is like this
Can anyone tell me why they are giving these two errors on the console? I do not know what to do
=\
As I can see - your application is not set-up properly. You don't have Redirect URL, Privacy Policy and because you are making API calls from JS - Origin URL:
So add something like:
Redirect URL: http://localhost:7000/redirect
Privacy Policy: http://localhost:7000/privacy
Origin URL: http://localhost:7000
I'm not sure where did you get your access token - because you don't have your app set up properly - but even then this will not work because your header is invalid. You are missing token type "Bearer" for access_token. So, in this case, your code should be like:
headers: {
Authorization: "Bearer KA.ey**********************************************************************************************************************************"
}
If you want to use Server Token:
headers: {
Authorization: "Token uberServerToken"
}
Please read our documentation for more info.

No 'Access-Control-Allow-Origin' header is present on the requested resource. - ionic

I'm trying to set up a HTTP-get request on my ionic application but i keep getting this error:
XMLHttpRequest cannot load http://www.wikicode.co.uk/announcement?
date=value2&message=value3&name=value1. No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://localhost:8100'
is therefore not allowed access.
I'm not really sure what's wrong. I've tried googling it but didn't have much luck.
Here's my code:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Announcement</title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="Announcement">
<ion-view view-title="Announcements">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Announcement</h1>
</ion-header-bar>
<br>
<br>
<br>
<ionic-content ng-controller="Controller">
<button class="button" ng-click="getData()">Do something</button>
<br>
name: {{name}} {{date}} {{message}}
</ionic-content>
</ion-pane>
</ion-view>
</body>
</html>
Javascript:
angular.module('starter.controllers', [])
.controller('announcementsCtrl', function($scope) {})
.controller('chatsCtrl', function($scope) {})
.controller('photosCtrl', function($scope) {})
.controller('profilesCtrl', function($scope) {})
.controller('Controller', function($scope, $http) {
$scope.getData = function() {
$http.get("http://www.wikicode.co.uk/announcement", { params: { "name": "value1", "date": "value2", "message": "value3"} })
.success(function(data) {
$scope.name = data.name;
$scope.date = data.date;
$scope.message = data.message;
})
.error(function(data) {
alert("ERROR");
});
}
});
This is a common issue with RESTful APIs that do not support CORS headers. You can work around this during development by using the proxy option in the Ionic CLI. I wrote a tutorial about this on my site http://ionicinaction.com/blog/how-to-fix-cors-issues-revisited/.
The big thing to remember is this only works for building the app. It does not solve the root of the problem. You have two options 1) get wikicode.co.uk to support CORS headers or 2) create another REST API that proxies to the real API but adds CORS headers. There are lots of ways to do #2, but here is how to build a simple Node server that does this. http://chafey.blogspot.com/2014/09/working-around-cors.html

How to specify accessToken for Mapbox with Leaflet

From Mapbox site I tested this code and success:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.cs
<style>
body { margin:0; padding:0; }
.map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map' class='map'> </div>
<script>
var map = new L.Map('map', {
center: new L.LatLng(51.505, -0.09),
zoom: 8,
layers: new L.TileLayer('https://a.tiles.mapbox.com/v3/mapbox.world-bright/{z}
});
</script>
</body>
</html>
How can I access my own map with markers and features? I suppose the "mapbox.world-bright" would be replaced by my own map.id, but how can I set the accessToken?
For some reasons I need to stick with Leaflet, and don't want to switch to mapbox.js.
It's just a matter of using the right url in L.TileLayer. You'll need to add your mapId and token and use the correct attribution. It's also much better if you load the tiles from multiple subdomains because your browser can handle up to four connection as once. Code example:
L.tileLayer('https://{s}.tiles.mapbox.com/v4/{mapId}/{z}/{x}/{y}.png?access_token={token}', {
attribution: '© Mapbox © OpenStreetMap',
subdomains: ['a','b','c','d'],
mapId: 'myMapId',
token: 'myUserToken'
});
To add the features of your map you'll need to query those in a separate request. Here's an example using jQuery. You'll need to swap the MAPID and TOKEN for your mapid and token ofcourse:
$.getJSON('http://a.tiles.mapbox.com/v4/MAPID/features.json?access_token=TOKEN', function (data) {
// Assuming the variable map contains your mapinstance
var geojson = L.geoJson(data).addTo(map);
map.fitBounds(geojson.getBounds());
});
Here's a working example on Plunker: http://plnkr.co/edit/h8F3kC?p=preview