Change code to google maps from openlayers - javascript

I am removing open layers and trying to use google maps instead. My javascript creates a layer as under
var options = {
"projection": new OpenLayers.Projection(DispProjection),
"strategies": [ new OpenLayers.Strategy.BBOX( {
"ratio": 2,
"resFactor": 3
} )
],
"protocol": new OpenLayers.Protocol.HTTP( {
"url": "kml.asmx",
"params": {},
"format": new OpenLayers.Format.KML( {
"extractStyles": true,
"extractAttributes": true,
"maxDepth": 2
} )
} )};
var itslayer = new OpenLayers.Layer.Vector(
l.name,
options );
The call to "kml.asmx" is in my .NET code which is a HttpHandler. To transform this code, how do I use the 'protocol' in google maps? I have tried to do this which clearly does not work
var itslayer = new google.maps.KmlLayer("kml.asmx");
Please help.

Related

How to access ArcGIS JavaScript API outside of require callback?

I am trying to figure out how I can access the ArCGIS JS API from a map after the map has been rendered, outside of require (ArcGIS JS API uses Dojo). For example, so I can do stuff like add (or remove) points, and perform other operations on the map.
I can create a map as follows:
require(["esri/config", "esri/Map", "esri/views/MapView", "esri/Graphic",
"esri/layers/GraphicsLayer"
], function(esriConfig, Map, MapView, Graphic, GraphicsLayer) {
esriConfig.apiKey = "";
const map = new Map({
basemap: "arcgis-topographic"
});
const view = new MapView({
map: map,
center: [-81, 41],
zoom: 9,
container: "viewDiv"
});
});
And I can add a point using this function:
function plotPoint(lat, long, props) {
const popupTemplate = {
title: "{Name}",
content: "{Description}"
}
const attributes = {
Name: props.name,
Description: props.desc
}
const graphicsLayer = new GraphicsLayer();
map.add(graphicsLayer);
const point = {
type: "point",
longitude: long,
latitude: lat
};
const simpleMarkerSymbol = {
type: "simple-marker",
color: [226, 119, 40],
outline: {
color: [255, 255, 255],
width: 1
}
};
const pointGraphic = new Graphic({
geometry: point,
symbol: simpleMarkerSymbol,
attributes: attributes,
popupTemplate: popupTemplate
});
graphicsLayer.add(pointGraphic);
}
But plotPoint needs to be within the require callback so it can access the referenced modules (like GraphicsLayer). I could assign it to the global window object so I could call it outside of require, but then I may run into an issue where the function is called before it's defined.
I may need to perform other operations too from other points in the code, like removing points, adding feature layers, etc. Unfortunately, this must all exist inside some legacy code, so I can't refactor the entire application.
Is there a better pattern for accessing the API outside of require?
I think that the easy way to achieve what you want, if I understand you correctly, is just to define modules and include it in you application.
A simple example base on you code would be something like this,
GraphicsManager.js
define([
"dojo/_base/declare",
"esri/Graphic",
"esri/layers/GraphicsLayer"
], function(declare, Graphic, GraphicsLayer){
return declare(null, {
plotPoint: function(lat, long, props){
// .. here the logic
return graphicsLayer;
}
});
});
main.js
require(["esri/config", "esri/Map", "esri/views/MapView", "app/GraphicsManager"
], function(esriConfig, Map, MapView, GraphicsManager) {
esriConfig.apiKey = "";
const map = new Map({
basemap: "arcgis-topographic",
});
const view = new MapView({
map: map,
center: [-81, 41],
zoom: 9,
container: "viewDiv"
});
// ... some logic to get the point data
const gm = new GraphicsManager();
map.add(gm.plotPoint(lat, long, props));
// .. some other logic
});
There you see that the main.js is where the application start, things are set there or in others modules. You know, map, layers, widgets, etc.
Then you have your other code in modules, and you use import them as required.
dojotoolkit - intro to modules

Openlayers map tiles are not initially loaded in single page app

I have a single page application built with
Express (4.16.3),
Openlayers (5.3) and
Pug (2.0.3 – formerly known as Jade) templating engine.
The map container is loaded and has child elements with ol- classes as well as the zoom controls in the upper left corner. So the Openlayers script is successfully executed. But it doesn't show the map tiles on load.
When I resize the browser the map tiles show up all of a sudden. So I'm wondering:
What is the event that triggers the sudden rendering of the tiles on browser resize, and how can I trigger it myself so the map is getting displayed correctly on load?
My index.pug looks like this:
doctype html
html(lang='de')
head
meta(charset='UTF-8')
meta(http-equiv='X-UA-Compatible', content='ie=edge')
meta(
name='viewport'
content='width=device-width, initial-scale=1')
title=`myTitle`
// Stylesheets
link(
rel='stylesheet',
href='https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css')
link(
rel='stylesheet',
href='/assets/style.css')
// Scripts
script(src='https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js')
script(src='https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList')
script(src='https://code.jquery.com/jquery-3.3.1.min.js')
script(data-main='/js/main', src='/js/require.js')
body
include header
include tabs
main
#loader Loading...
include map
include footer
And in the main part you see the map pug template included that looks like this:
section.component#component-map
#map.map
script.
/**
* Leaflet Map
*/
// Create markers and geodata
const mapCenter = [13.429, 52.494];
const siteData = !{JSON.stringify(sites)};
const features = siteData.map(site => {
return {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ Number(site.longitude), Number(site.latitude) ]
}
}
});
const image = new ol.style.Circle({
radius: 5,
fill: null,
stroke: new ol.style.Stroke({color: "red", width: 1})
});
const styles = {
"Point": new ol.style.Style({
"image": image
})
}
const styleFunction = function(feature) {
return styles[feature.getGeometry().getType()];
};
const geojsonObject = {
"type": "FeatureCollection",
"features": features
};
const vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
const vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunction
});
const map = new ol.Map({
target: "map",
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
view: new ol.View({
center: ol.proj.fromLonLat(mapCenter),
zoom: 17,
})
});
Found the answer myself. My "solution" is more of a workaround than an actual solution. I wait for the map script to be executed (which is the case when the map container has a child element with class name ol-viewport) and then I trigger the browser resize event manually. Other than I expected, the map.render() or map.renderSync() methods do not load the tiles.
So the workaround looks like this:
const waitForMap = setInterval(function() {
if ($('.ol-viewport').length) {
console.log("Exists!");
window.dispatchEvent(new Event('resize'));
clearInterval(waitForMap);
}
}, 100);
A bit ugly but this solution saved me. I'm not using jQuery so replaced .length() with:
const waitForMap = setInterval(function() {
const e = document.querySelector(".ol-viewport");
const cr = e.getClientRects();
if ((cr.length != 0) && (cr[0].width != 0) && (cr[0].height != 0)) {
console.log("Render OpenLayer map");
window.dispatchEvent(new Event('resize'));
clearInterval(waitForMap);
}
}, 500);

How to use API translate of SAP Leonardo?

I need help with API translation of SAP Leonardo. I building a translation app for studing, and following the documentation a create the method translate:
translate: function () {
//Create JSON Model with URL
var oModel = new sap.ui.model.json.JSONModel();
var langTo = this.getView().byId("idTo").getSelectedKey();
var langFrom = this.getView().byId("idFrom").getSelectedKey();
var textOld = this.getView().byId("idOldText").getValue();
//API Key for API Sandbox
var sHeaders = {
"Content-Type": "application/json",
"APIKey": "My api Key"
};
//Available Security Schemes for productive API Endpoints
//OAuth 2.0
//sending request
//API endpoint for API sandbox
var oData = {
"sourceLanguage": langTo,
"targetLanguages": [
langFrom
],
"units": [{
"value": textOld,
"key": "ANALYZE_SALES_DATA"
}]
};
oModel.loadData("https://sandbox.api.sap.com/ml/translation/translation", oData, true, "POST", null, false, sHeaders);
//Available API Endpoints
//https://mlfproduction-machine-translation.cfapps.eu10.hana.ondemand.com
//https://mlfproduction-machine-translation.cfapps.us10.hana.ondemand.com
//You can assign the created data model to a View and UI5 controls can be bound to it. Please refer documentation available at the below link for more information.
//https://sapui5.hana.ondemand.com/#docs/guide/96804e3315ff440aa0a50fd290805116.html#loio96804e3315ff440aa0a50fd290805116
//The below code snippet for printing on the console is for testing/demonstration purpose only. This must not be done in real UI5 applications.
oModel.attachRequestCompleted(function (oEvent) {
var oData = oEvent.getSource().oData;
// console.log(oData);
});
}
I used two selectBox for to get language keys both calls "idTo" and "idFrom". And I used too a input for get a text will be translate with id "idOldText". But nothing happen. the oData value always empty in the last instruction. I'm used SAP WEBIDE and I guess that it is not need configure IDE for to use the API.
Someone can help me?
it would be helpful if you provide the error from your console.
But I already have a feeling that this ends up in a cross site request, and thus will be blocked because of using a full qualified URL. Also your header whitelist is maybe missing.
Do it like this and it should work:
1) create a destination in SAP CP
2) create a new sapui5 project in SAP WebIDE and adapt neo-app.json by addin a new destination path and header whitelist your request headers
{
"welcomeFile": "/webapp/index.html",
"routes": [{
"path": "/resources",
"target": {
"type": "service",
"name": "sapui5",
"entryPath": "/resources"
},
"description": "SAPUI5 Resources"
}, {
"path": "/test-resources",
"target": {
"type": "service",
"name": "sapui5",
"entryPath": "/test-resources"
},
"description": "SAPUI5 Test Resources"
}, {
"path": "/ml-dest",
"target": {
"type": "destination",
"name": "sapui5ml-api"
},
"description": "ML API destination"
}],
"sendWelcomeFileRedirect": true,
"headerWhiteList": [
"APIKey", "Accept", "Content-Type"
]
}
3) add your method and post the request || possible issues in your version: JSON object and request headers
onInit: function () {
var oModel = new sap.ui.model.json.JSONModel();
var sHeaders = {
"Content-Type": "application/json",
"Accept": "application/json",
"APIKey": "<<yourAPIKey>>"
};
var oData = {
"sourceLanguage": "en",
"targetLanguages": [
"de"
],
"units": [{
"value": "I would like to analyze my sales data.",
"key": "ANALYZE_SALES_DATA"
}]
};
var ODataJSON = JSON.stringify(oData);
oModel.loadData("/ml-dest/translation/translation", ODataJSON, true, "POST", null, false, sHeaders);
oModel.attachRequestCompleted(function (oEvent) {
var oData = oEvent.getSource().oData;
console.log(oData.units[0].translations[0]);
});
}
4) get a successful response object when loading your app :-)
References used:
Destination creation (my own blog entry btw.) https://blogs.sap.com/2018/09/05/successfactors-extensions-with-sapui5-and-the-correct-usage-of-sap-cp-destination-services/
SAPUI5 examples for SAP ML Inference Services (see multiple examples) https://developers.sap.com/tutorials/ml-fs-sapui5-img-classification.html

Loading OpenLayers Features without loading and displaying the whole surrounding map

var config = {
geoserver: "http://url/geoserver/",
wms_layer: "tt/wms?service=WMS",
wfs_layer: "tt/wfs",
featureNS: "url2",
init_center : new OpenLayers.Bounds(363273.29099999997,5770864.300999998),
init_zoom : 4,
maxExtent: new OpenLayers.Bounds(363052,5770362,363467,5771122)
};
map = new OpenLayers.Map({
div:"map",
//zoom:0,
projection: new OpenLayers.Projection(epsg),
units: "m",
maxResolution: 2,
maxExtent: config.maxExtent,
});
var layer_selectable = new OpenLayers.Layer.Vector("WFS", {
strategies : [new OpenLayers.Strategy.BBOX(),saveStrategy],
protocol: new OpenLayers.Protocol.WFS({
url: config.geoserver + config.wfs_layer,
version: "1.1.0",
featureType: "ftype",
featureNS: config.featureNS,
srsName: epsg
}),
renderers: renderer
});
function doSomething() {
var myFeatures = layer_selectable.getFeaturesByAttribute("fid","<?= $fid ?>");
alert(myFeatures);
}
layer_selectable.events.register("loadend", layer_selectable,doSomething);
map.addLayers([layer_selectable]);
map.setCenter(config.init_center.getCenterLonLat(),config.init_zoom);
I am absolutely new to OpenLayers. I found this code. What I want now, is to retrieve the 'myFeatures' data from the webserver without having to load and display the whole Map and the layer. Is there an easy way to do that?

OpenLayers getFeatureInfo popup generates this.size is null

I am trying to create OpenLayers with popup feature info. I got the code from OpenLayers examples and only modified url to my local geoserver. The map is displaying, when i click on a feature the request is sent but the response is empty and firebug shows error "this.size is null". When i run the request url separately feature info is generated.
Here is the code:
var map, info;
function load() {
map = new OpenLayers.Map({
div: "map",
maxExtent: new OpenLayers.Bounds(20.163,53.228,20.208,53.257)
//maxExtent: new OpenLayers.Bounds(143.834,-43.648,148.479,-39.573)
//maxExtent: new OpenLayers.Bounds(19,90,19,90)
});
var punkty_zdjecia = new OpenLayers.Layer.WMS("Punkty Zdjecia",
"http://localhost:6060/geoserver/wms",
{'layers': 'cite:ulice2', transparent: false, format: 'image/gif'},
{isBaseLayer: true}
);
map.addLayers([punkty_zdjecia]);
info = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost:6060/geoserver/wms',
title: 'Test url',
queryVisible: true,
eventListeners: {
getfeatureinfo: function(event) {
map.addPopup(new OpenLayers.Popup.FramedCloud(
"chicken",
map.getLonLatFromPixel(event.xy),
new OpenLayers.Size(200,200),
event.text,
null,
true
));
}
}
});
map.addControl(info);
info.activate();
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToMaxExtent();
}
I am using OpenLayers 2.11 and Firefox browser

Categories

Resources