How to enable Global settings in geoserver - ajax

I have been trying to implement wfs-t service in openlayers3 in system. I can able to see the
<wfs:FeatureCollection xmlns="http://www.opengis.net/wfs" xmlns:wfs="http://www.opengis.net/wfs" xmlns:sf="http://www.openplans.org/spearfish" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd http://www.openplans.org/spearfish http://localhost:9999/geoserver/sf/wfs?service=WFS&version=1.0.0&request=DescribeFeatureType&typeName=sf%3AAPRoad50MMI2015">
<gml:boundedBy>
<gml:Box srsName="EPSG:4326">
<gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">76.771293,12.625601 84.727878,19.166098</gml:coordinates>
</gml:Box>
My XML for the delete from my geoserver with featureID are:
<Transaction xmlns="http://www.opengis.net/wfs" service="WFS" version="1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"><Delete typeName="feature:jktouristspots50poi2015" xmlns:feature="http://172.31.4.67:9999/geoserver/mywork"><Filter xmlns="http://www.opengis.net/ogc"><FeatureId fid="jktouristspots50poi2015.55"/></Filter></Delete></Transaction>
1. My geoserver deatails:
Build Information
GeoServer Version
2.11.1
Git Revision
0628848420a522efc1c6bbd90cb3346038929f6a
Build Date
18-May-2017 22:36
GeoTools Version
17.1 (rev 86d8efab5104df08c81acf7b2f2342e08c9dea4b)
GeoWebCache Version
1.11.0 (rev 1.11.x/02b79570ae64d548f9fb39bcab5edc9cb4d0c992)
For the above WFS request i have set my ajax function like below:
<script type="text/javascript">
var formatWFS = new ol.format.WFS();
var formatGML = new ol.format.GML({
featureNS: 'http://localhost:9999/geoserver/mywork',
featureType: 'jktouristspots50poi2015',
srsName: 'EPSG:4326'
});
alert("GML",formatGML);
var xs = new XMLSerializer();
var sourceWFS = new ol.source.Vector({
loader: function (extent, resolution, projection) {
var url = 'http://localhost:9999/geoserver/mywork/wfs?service=WFS&' +
'version=1.1.0&request=GetFeature&typename=mywork:jktouristspots50poi2015&' +
'outputFormat=text/javascript&srsname=EPSG:4326&' +
'bbox=' + extent.join(',') + ',EPSG:4326';
alert(url);
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'callback:loadFeatures',
jsonp: 'format_options'
}).done(function (response) {
alert("i am done");
});
},
strategy: ol.loadingstrategy.bbox
});
window.loadFeatures = function (response) {
layerWFS
.getSource()
.addFeatures(new ol.format.GeoJSON().readFeatures(response));
};
var layerWFS = new ol.layer.Vector({
source: sourceWFS
});
var interaction;
var interactionSelectPointerMove = new ol.interaction.Select({
condition: ol.events.condition.pointerMove
});
var interactionSelect = new ol.interaction.Select({
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#FF2828'
})
})
});
var interactionSnap = new ol.interaction.Snap({
source: layerWFS.getSource()
});
var map = new ol.Map({
target: 'map',
controls: [],
interactions: [
interactionSelectPointerMove,
new ol.interaction.MouseWheelZoom(),
new ol.interaction.DragPan()
],
layers: [
new ol.layer.Tile({
title: 'India',
source: new ol.source.TileWMS({
url: 'http://ndem.nrsc.gov.in/geoserver_v3/ndem50k/wms',
params: {LAYERS: 'ndem50k:stateadmin50census2011'}
})
}),
layerWFS
],
view: new ol.View({
projection: 'EPSG:4326',
center: [82.491,21.899],
zoom: 5
})
});
//wfs-t
var dirty = {};
var transactWFS = function (mode, f) {
var node;
switch (mode) {
case 'insert':
node = formatWFS.writeTransaction([f], null, null, formatGML);
alert("after insert node",node);
break;
case 'update':
node = formatWFS.writeTransaction(null, [f], null, formatGML);
break;
case 'delete':
node = formatWFS.writeTransaction(null, null, [f], formatGML);
break;
}
var payload = xs.serializeToString(node);
<!-- '<Transaction xmlns="http://www.opengis.net/wfs" service="WFS" version="1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"><Delete typeName="feature:jktouristspots50poi2015" xmlns:feature="http://172.31.4.67:9999/geoserver/mywork"><Filter xmlns="http://www.opengis.net/ogc"><FeatureId fid="jktouristspots50poi2015.55"/></Filter></Delete></Transaction>'; -->
alert(payload);
$.ajax('http://localhost:9999/geoserver/mywork/ows', {
service: 'WFS',
type: 'POST',
dataType: 'xml',
processData: true,
contentType: 'text/xml',
data: {data:payload}
}).done(function() {
alert("gekki hi ");
console.log("indside done");
sourceWFS.clear();
});
alert("out i am"+payload);
};
$('button').click(function () {
alert();
$(this).siblings().removeClass('btn-active');
$(this).addClass('btn-active');
map.removeInteraction(interaction);
interactionSelect.getFeatures().clear();
map.removeInteraction(interactionSelect);
switch ($(this).attr('id')) {
case 'btnEdit':
map.addInteraction(interactionSelect);
interaction = new ol.interaction.Modify({
features: interactionSelect.getFeatures()
});
alert("am edit "+interaction);
map.addInteraction(interaction);
map.addInteraction(interactionSnap);
dirty = {};
interactionSelect.getFeatures().on('add', function (e) {
e.element.on('change', function (e) {
//alert("i am add ");
dirty[e.target.getId()] = true;
});
});
interactionSelect.getFeatures().on('remove', function (e) {
var f = e.element;
if (dirty[f.getId()]) {
alert("i am in remove");
delete dirty[f.getId()];
var featureProperties = f.getProperties();
delete featureProperties.boundedBy;
var clone = new ol.Feature(featureProperties);
clone.setId(f.getId());
transactWFS('update', clone);
}
});
break;
case 'btnPoint':
interaction = new ol.interaction.Draw({
type: 'Point',
source: layerWFS.getSource()
});
map.addInteraction(interaction);
interaction.on('drawend', function (e) {
transactWFS('insert', e.feature);
});
break;
case 'btnLine':
alert("line feature draw");
interaction = new ol.interaction.Draw({
type: 'LineString',
source: layerWFS.getSource()
});
map.addInteraction(interaction);
interaction.on('drawend', function (e) {
var myAttrValue = prompt("Enter Attribute", "");
var myFeature= e.feature;
if (myAttrValue != null) {
myFeature.set('column', myAttrValue);
}
transactWFS('insert', myFeature);
});
break;
case 'btnArea':
interaction = new ol.interaction.Draw({
type: 'Polygon',
source: layerWFS.getSource()
});
interaction.on('drawend', function (e) {
transactWFS('insert', e.feature);
});
map.addInteraction(interaction);
break;
case 'btnDelete':
interaction = new ol.interaction.Select();
interaction.getFeatures().on('add', function (e) {
transactWFS('delete', e.target.item(0));
interactionSelectPointerMove.getFeatures().clear();
interaction.getFeatures().clear();
});
map.addInteraction(interaction);
break;
default:
break;
}
});
</script>
How can i enable global setting in geoserver, what is ows? If i pass the existing path also its throwing error like:
PATH OF MY WORKSPACE IN GEOSERVER:
C:\Program Files (x86)\GeoServer 2.11.1\data_dir\workspaces\mywork\jktourisam
wfs-t.jpg
postgislayer.html:1 XMLHttpRequest cannot load http://localhost:9999/geoserver/mywork/wfs.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 403.
I have tried many ways, i couldn't find the solution.......
I was able to view the added WFS vector layer on my map. Is there any parameter wrong in my code? Mean while i have tested WFS-T with same url of layer from my geoserver, at there also i cant delete and insert features to geoserver and postgres, but i can able to draw on map by using that polygon,line and point features on map and can able to retrieve the feature id? I want to implement CQL and ECQL filters also in my code kindly provide any reference links to learn. Thank you
Mean while alerting success from ajax call(POST) is also not working, i think it was because of the wrong url i am pass? Is it correct? Please guide me to set environment in geoserver to perform wfs-t..

You need to enable CORS in your container. See this question if you are using Jetty as your container, or this question if you use tomcat.

Related

Pass image through ajax using cordova

I am developing my mobile application using ionic framework and I want it to connect to my API through ajax. Currenty, in the mobile side, which is I am using Ionic Framework, I want to upload an image and pass it to my api through ajax. I am using Cordova for the upload but it seems it doesn't found the URL I indicated.
Here's the HTML
<ion-footer-bar class="bar bar-positive">
<div class="button-bar">
<button class="button icon-left ion-upload" ng-click="uploadImage()" ng-disabled="image === null">Upload</button>
</div>
</ion-footer-bar>
Here's the uploadImage() function in the controller (Just copied the code in a site. Forgot where) EDIT: added targetPath
$scope.uploadImage = function() {
// Destination URL
var url = "http://192.168.0.19/identificare_api/public/api/plants/image";
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
var jsonparse = JSON.parse(result);
$scope.showAlert(jsonparse);
}
But in the upload part, I want to do it in ajax to indicate the method for the URL but the problem I don't know what put in data.
$.ajax({
url: "http://192.168.0.19/identificare_api/public/api/plants/image",
type: 'POST',
data:
success:function(json){
var jsonparse = JSON.parse(json);
alert(jsonparse);
},
error:function(){
alert("Error");
}
});
Can someone help me with this issue?
UPDATE: Applied here #Blauharley's comment below
I had another issue here. I returned the $_FILES['image']['tmp_name'] in the API side but it returns nothing but when I returned the $_FILES['image']['name'], it returned my_image.jpg. Why it doesn't have tmp_name?
$scope.uploadImage = function() {
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
$scope.getBase64ImageByURL(targetPath).then(function(base64Image){
var blob = $scope.base64ToBlob(base64Image,'image/jpeg');
var fd = new FormData();
fd.append('image', blob, "my_image.jpg");
fd.append('user_token', "rLUrh37rfTozuBxmemHtlKMgH");
$.ajax({
url: 'http://192.168.0.19/identificare_api/public/api/plants/image',
type: 'POST',
data: fd,
contentType: false,
processData: false,
success:function(res){
alert(res);
},
error:function(err){
alert("Something's wrong with your api. Come on fix it!");
}
});
});
};
$scope.getBase64ImageByURL = function(url) {
var dfd = new $.Deferred();
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
dfd.resolve(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
return dfd.promise();
};
$scope.base64ToBlob = function(base64Image,toMimeType) {
var byteCharacters = atob(base64Image.replace('data:'+toMimeType+';base64,',''));
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: toMimeType
});
return blob;
};
ADDED: API side
public function image(){
echo json_encode($_FILES['image']['tmp_name']);
}

How can I handle a ajax request response in the Flux Architecture?

Looking at the Flux Documentation I can't figure out how the code to a ajax update, and a ajax fetch would fit into the dispatcher, store, component architecture.
Can anyone provide a simple, dummy example, of how an entity of data would be fetched from the server AFTER page load, and how this entity would be pushed to the server at a later date. How would the "complete" or "error" status of request be translated and treated by the views/components? How would a store wait for the ajax request to wait? :-?
Is this what you are looking for?
http://facebook.github.io/react/tips/initial-ajax.html
you can also implement a fetch in the store in order to manage the information.
Here is an example (it is a concept, not actually working code):
'use strict';
var React = require('react');
var Constants = require('constants');
var merge = require('react/lib/merge'); //This must be replaced for assign
var EventEmitter = require('events').EventEmitter;
var Dispatcher = require('dispatcher');
var CHANGE_EVENT = "change";
var data = {};
var message = "";
function _fetch () {
message = "Fetching data";
$.ajax({
type: 'GET',
url: 'Url',
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = error;
MyStore.emitChange();
}
});
};
function _post (myData) {
//Make post
$.ajax({
type: 'POST',
url: 'Url',
// post payload:
data: JSON.stringify(myData),
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = "update failed";
MyStore.emitChange();
}
});
};
var MyStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getData: function (){
if(!data){
_fetch();
}
return data;
},
getMessage: function (){
return message;
},
dispatcherIndex: Dispatcher.register( function(payload) {
var action = payload.action; // this is our action from handleViewAction
switch(action.actionType){
case Constants.UPDATE:
message = "updating...";
_post(payload.action.data);
break;
}
MyStore.emitChange();
return true;
})
});
module.exports = MyStore;
Then you need to subscribe your component to the store change events
var React = require('react');
var MyStore = require('my-store');
function getComments (){
return {
message: null,
data: MyStore.getData()
}
};
var AlbumComments = module.exports = React.createClass({
getInitialState: function() {
return getData();
},
componentWillMount: function(){
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function(){
MyStore.removeChangeListener(this._onChange);
},
_onChange: function(){
var msg = MyStore.getMessage();
if (!message){
this.setState(getData());
} else {
this.setState({
message: msg,
data: null
});
}
},
render: function() {
console.log('render');
return (
<div>
{ this.state.message }
{this.state.data.map(function(item){
return <div>{ item }</div>
})}
</div>
);
}
});
I hope it is clear enough.

Ajax Request with Googlemap API

I'm building a page that will display a Googlemap with markers. Since I have about 50000 markers, I decided not to load them all at once.
Therefore I tried building an JSON request to my server (see code below) but here is my problem:
When I use the code as it is presented here, the Map is blank (no Map shows up).
When I remove the $.ajax and leave the function getMarkers emtpy, the map shows properly (whitout marker of course).
Can anyone tell me what I'm doing wrong please?!
Thank you!
(If that is any help, I'm using Django)
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function init_map() {
var mapOptions = {
center: new google.maps.LatLng(48.853,2.35),
zoom: 6,
streetViewControl: false,
};
var myMap = new google.maps.Map(document.getElementById("map-container"),mapOptions);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(myMap, 'idle', getMarkers);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
}
google.maps.event.addDomListener(window, 'load', init_map);
function getMarkers() {
$.ajax({
type: 'POST',
url: {%url 'pointslink'%},
async: "true",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(
coords: myMap.getBounds(),
zoom: myMmap.getZoom()
),
success: updateMarkers
});
}
function updateMarkers(data) {
{% for city in data %}
var pos = new google.maps.LatLng({{city.latitude}},{{city.longitude}});
var marker = new google.maps.Marker({
position: pos,
map: myMap,
title:'{{city.name}}'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('Name: {{city.name}}<br/>Population: {{city.population}}');
infowindow.open(myMap, this);
});
{%endfor%}
}
</script>

ember ajax calls with promisses access result in templates and controller

I'm making a call to the server to get some data via an ajax request and I use a promise. While my template automatically updates as soon as the data is returned, I'm unlucky accessing the data in the controller, as I don't know exactly when it's there.
To resolve I can make an additional ajax call in the controller to get the same data but that feels ugly. Is there a nicer way to know when to access the data in the controller? As a work around I tried to call the function that needs the data on the didInsertElement but that didn't solve it.
App.ActiveDataSet = Ember.Object.extend({
progress: 0
});
App.ActiveDataSet.reopenClass({
findAll: function(project_id) {
var result = [];
$.ajax({
url: '/active_data_sets.json',
type: 'GET',
data: {'project_id': project_id}
}).then(function(response) {
response.active_data_sets.forEach(function(newset) {
result.addObject(App.ActiveDataSet.create(newset));
});
});
return result;
}
});
App.MapviewShowRoute = Ember.Route.extend({
setupController: function(controller, model) {
this.controllerFor('activedatasetIndex').set('content', App.ActiveDataSet.findAll(model.id));
}
});
App.MapviewShowController = Ember.ObjectController.extend({
needs: ['activedatasetIndex'],
content: null,
dataSets: [],
createDataSets: function() {
// create the datasets
for (var counter = 0; counter < this.get('controllers.activedatasetIndex.content').length; counter++) {
alert(dataSets[counter].ds.name);
}
}
});
App.MapviewShowView = Ember.View.extend({
map: null,
didInsertElement: function() {
var map = null;
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(52.368892, 4.875183),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(this.$('#map_canvas').get(0), myOptions);
this.set('map', map); //save for future updations
var h = $(window).height(),
offsetTop = 60; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
// get the datasets
this.controller.createDataSets();
}
});
Have you tried continuing the promises chain:
App.ActiveDataSet.reopenClass({
findAll: function(project_id) {
return $.ajax({
url: '/active_data_sets.json',
type: 'GET',
data: {'project_id': project_id}
}).then(function(response) {
var result = [];
response.active_data_sets.forEach(function(newset) {
result.addObject(App.ActiveDataSet.create(newset));
});
return result;
});
}
});
App.MapviewShowRoute = Ember.Route.extend({
setupController: function(controller, model) {
App.ActiveDataSet.findAll(model.id).then(function(content) {
this.controllerFor('activedatasetIndex').set('content', content);
});
}
});

Missing dynamic Markers GMaps V3

I have written some code to fetch zipcodes from a mysql db via ajax call, geocode them, then make markers out of them on a GMap. The markers are clickable to reveal some demographic data. It works if i leave the alert in the each loop uncommented. If not it only shows about 8 markers. Any and all help is appreciated. Relevant code:
function initialize() {
var geocoder = new google.maps.Geocoder();
var markers = [];
var latlng = new google.maps.LatLng("33.7463915", "-117.86044720000001");
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.ajax({
url: 'getzips.php',
dataType: 'json',
success: function (data) {
$.each(data.rows, function(i, item) {
//alert(item.zip);
if (geocoder) {
geocoder.geocode({ 'address': item.zip }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: item.zip
});
var infowindow = new google.maps.InfoWindow({
content: item.zip
});
google.maps.event.addListener(marker, "click", function() {
$.ajax({
url: 'getinfo.php?zipcode=' + marker.title,
success: function(data){
infowindow.setContent(data);
infowindow.open(map, marker);
}
});
});
markers.push(marker);
}
});
}
else
alert("geocode error");
});
}
});
//alert(markers.length);
}
Google Geocoding API has both query and rate limits. You need to slow down when querying.
Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day.
Additionally, we enforce a request rate limit to prevent abuse of the service.

Resources