how to get coordinate lon lat from geoserver with openlayers3 - openlayers-3

I run this code to get all of my vector coordinates:
var ft = vectorSource[0].getFeatures();
for(var i=0; i< ft.length; i++){
document.getElementById('abc').innerHTML+=vectorSource[0].getFeatures()[i].getGeometry().transform('EPSG:3857','EPSG:4326').getCoordinates()
};
This is the result:
106.68594471683284,-6.145608605008391,106.68637254034257,-6.145584973628701
How can I get two numbers representing lon & lat from my vector?
i need result coordinate like following code from all my vector but without click the map
map.on('singleclick', function(evt) {
var coordinate = evt.coordinate;
});

Related

Using GSheets Script to increment value of duplicate by 1

I want to check a row for duplicates and if match increment these by 1.
The data I want to manipulate this way is LAT LONG Coordinates.
They originate from an aggregated data acquisition, where users can only insert country and city. Via an Add-On these will get GEO coded.
Problem is, that I need to slightly change the values of duplicate entries, in order to display them on a map. Easiest way (I think) is to increment a LAT or LONG coordinate by 1 if there is already an entry with the same value.
Data sample & results of script
Any idea how to do this via Script?
My code, originally intended to delete duplicate rows:
function overwriteDuplicates() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("Formularantworten 2");
var vA=sh.getDataRange().getValues();
var hA=vA[0];
var hObj={};
hA.forEach(function(e,i){hObj[e]=i;});//header title to index
var uA=[];
var d=0;
for(var i=0;i<vA.length;i++) {
if(uA.indexOf(vA[i][hObj['Latitude']])==-1) {
uA.push(vA[i][hObj['Latitude']]);
}else{
function increment() {
SpreadsheetApp.getActiveSheet().getRange('K').setValue(SpreadsheetApp.getActiveSheet().getRange('K').getValue() + 1);
}
}}}
You want to modify the latitude whenever duplicate coordinates (latitude and longitude is found).
In this case, you can do the following:
Get all the values in the sheet, and retrieve the indexes where Latitude and Longitude are, based on the headers.
Loop through all rows (excluding headers), and for each row, check whether a previous row contains these coordinates.
If that's the case (isDuplicate), increment the last number in the latitude (after the last .), or decrement it if it's close to 999 (I assume there's always 3 digits).
Store the new latitude in an array after modification.
Use setValues to write the modified latitudes to the sheet.
Below is a possible code snippet to do this (see inline comments for details).
Code snippet:
function overwriteDuplicates() {
const ss = SpreadsheetApp.getActive();
const sheet = ss.getSheetByName("Formularantworten 2");
const values = sheet.getDataRange().getValues();
const headers = values.shift(); // Retrieve first row (headers)
const latColumn = headers.indexOf("Latitude"); // Latitude column index
const longColumn = headers.indexOf("Longitude"); // Longitude column index
let outputLocations = [];
for (let i = 0; i < values.length; i++) { // Loop through rows
const newLocation = { // Store object with current location
"latitude": values[i][latColumn],
"longitude": values[i][longColumn]
}
let isDuplicate;
do { // Check if location is duplicate, and increment if necessary
isDuplicate = outputLocations.some(location => {
const sameLatitude = location["latitude"] === newLocation["latitude"];
const sameLongitude = location["longitude"] === newLocation["longitude"];
return sameLatitude && sameLongitude;
});
if (isDuplicate) newLocation["latitude"] = modifyCoord(newLocation["latitude"]);
} while (isDuplicate);
outputLocations.push(newLocation); // Store new location in array
}
let outputLatitudes = outputLocations.map(location => [location["latitude"]]); // Retrieve latitudes from array
sheet.getRange(2, latColumn+1, sheet.getLastRow()-1).setValues(outputLatitudes); // Write updated latitudes to sheet
}
function modifyCoord(coordinates) {
let coordArray = coordinates.split(".");
let lastCoord = coordArray.pop();
if (lastCoord > 990) lastCoord--;
else lastCoord++;
coordArray.push(lastCoord);
return coordArray.join(".");
}
Output:

GeoLocation - Center a map

I am creating a map with markers with the leaflet library.
var mymap = L.map('mapid', {
center: [${mapCenter.lat}, ${mapCenter.lng}],
zoom: 9
});
I am using this algorithm to calculate the center of the map based in all the markers I have to show
double minLatitude = Double.MAX_VALUE;
double maxLatitude = Double.MIN_VALUE;
double minLongitude = Double.MAX_VALUE;
double maxLongitude = Double.MIN_VALUE;
for (ViewMarker marker : markers) {
if (marker.getLng() > maxLongitude) {
maxLongitude = marker.getLng();
}
if (marker.getLng() < minLongitude) {
minLongitude = marker.getLng();
}
if (marker.getLat() > maxLatitude) {
maxLatitude = marker.getLat();
}
if (marker.getLat() < minLatitude) {
minLatitude = marker.getLat();
}
}
double centerLatitude = (minLatitude + maxLatitude ) / 2;
double centerLongitude = (minLongitude + maxLongitude) / 2;
But as you see in the image, I wouldn't say that the map is in the center
Instantiate a L.LatLngBounds, insert the markers' LatLngs there, and then do a map.fitBounds().
Alternatively, use a FeatureGroup to hold all the markers inside, as it provides a getBounds().
Unless you know the basics of geodesy and map projections, do not use naïve solutions like centerlat = (lat1 + lat2) / 2, which is not true for the default Mercator projection.

How do I check if location is on the polyline (Here maps)?

I search a method to find if my current location is on the path define by aPolyline.
In google maps a function exist isLocationOnEdge, but I cannot find a similar function in Here maps API.
This could be achieved using an approach an below
//global variable
var polyline;
polyline = new H.map.Polyline(strip);
map.addObject(polyline);
function liesOnPolyline(coords){
// get objects at the coordinates (pixel coordinates, can be converted from lat, lon using map.geoToScreen )
var objects = map.getObjectsAt(coords.x, coords.y);
// iterate through the array to check if polyline can be retrieved here
var withinPolyline = false;
for (var object in objects) {
if(objects[object] === polyline){
withinPolyline = true;
break;
}
}
console.log("lies within Polyline"+withinPolyline );
}

How to convert a OPENLAYERS 3 postcompose method to a normal one?

I am trying to animate a line based on the given coordinates array comprising of latitude and longitude and I want to call my function just once and my coordinates name is: replayData.
map.on('postcompose', function (event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
vectorContext.setFillStrokeStyle(null, animatedLineStroke);
var features = lineVectorSource.getFeatures();
for (var k = 0; k < features.length; k++) {
var feature = features[k];
if (!feature.get('finished')) {
var coords = feature.getGeometry().getCoordinates();
var elapsedTime = frameState.time - feature.get('start');
var elapsedPoints = elapsedTime * pointsPerMs;
if (elapsedPoints >= coords.length) {
feature.set('finished', true);
}
var maxIndex = Math.min(elapsedPoints, coords.length);
var currentLine = new ol.geom.LineString(coords.slice(0, maxIndex));
if (feature.get('iValue') == undefined || feature.get('iValue') < k) {
// drawMovingCarMarker(coords, k);
feature.set('iValue', k)
}
vectorContext.drawLineStringGeometry(currentLine, feature);
}
}
frameState.animate = true;
});
What this function is doing is first collecting all the values from for loop and then starting the animation. And because of this if I've 5 points the line between first two points will be drawn 5 times then 4,3, and so on.
Any help would be entertained. Thanks in advance.

Convert point to lat lon

I wonder, how can I get map click event's coordinates as lat,lon?
Here is my code:
map.on('click', function(evt) {
var element = popup.getElement();
var coordinate = evt.coordinate;
var latLon = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326');
$(element).popover('destroy');
popup.setPosition(coordinate);
Normally, coordinate value gives me an array etc: [48654.02545, 3265468.45455]
But I need lat lon etc:([39,54876,32,547821])
Abstract: I need to convert epsg:3857 coordinate to epsg:4326 coordinate (lat/lon)
Any idea?
If your map view projection is Web Mercator (EPSG:3857), which is the default, then the following should work:
map.on('click', function(evt) {
var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
var lon = lonlat[0];
var lat = lonlat[1];
// …
});

Resources