This question involves the use of:
leaflet.js (used to create my map)
leaflet omnivore plugin (used to load my csv data file)
and proj4 (used to convert easting/northing to lat/lon)
My code below loads a stamen map with leaflet, and then uses omnivore to load my csv file.
In order to display the csv geo data on my map i need to first convert the easting/northing coordinates to lat/lon. The next sections of code contain the logic to do this, and it works successfully for the single coordinate sample within the console.log at the bottom.
But I have no idea how to use this logic on my full csv file. There is one column for easting, one for northing in the file - ultimately i want to my code to convert all these to lat lon, and plot them as points on my map.
var map = L.map('map').setView([51.44, -1.01], 8);
L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner-background/{z}/{x}/{y}.{ext}',
{
subdomains: 'abcd',
minZoom: 8,
maxZoom: 20,
ext: 'png'
}).addTo(map);
var dataset = omnivore.csv('assets_cwy_new simple.csv');
var osgb = '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs ';
var wgs84 = '+proj=longlat +datum=WGS84 +no_defs ';
console.log(proj4(osgb,wgs84,[514545.49,215008.4]));
As you figured out, you can use Proj4Leaflet plugin with Proj4js to convert your easting/northing coordinates into WGS84 lng/lat. Do not forget to revert the coordinates into lat/lng for Leaflet.
Now to have leaflet-omnivore use the correct columns from your CSV file, you have to use the parser_options (2nd parameter of your call to omnivore.csv), which are actually passed to the underlying library csv2geojson. These options let you specify the latitude and longitude fields of your CSV file. For now you have only easting/northing, but we can convert them later on:
var csv2geojsonOptions = {
latfield: 'northing',
lonfield: 'easting',
delimiter: ','
}
omnivore.csv('./assets_cwy_new_simple.csv', csv2geojsonOptions);
Next, you need to convert your easting/northing coordinates into WGS84 lng/lat coordinates, using proj4leaflet. To have omnivore perform this conversion on each of your lines, you have to use the customLayer (3rd parameter of your call to omnivore.csv). It is actually just a preconfigured Leaflet GeoJSON Layer Group. With this group, you can use its coordsToLatLng option to implement your conversion with proj4leaflet:
var customLayer = L.geoJSON(null, {
coordsToLatLng: projCoordsToLatLng
});
function projCoordsToLatLng(coords) {
return lngLatToLatLng(proj4(osgb, wgs84, coords));
}
function lngLatToLatLng(lngLat) {
return [lngLat[1], lngLat[0]];
}
omnivore.csv('./assets_cwy_new_simple.csv', csv2geojsonOptions, customLayer);
Live example: https://plnkr.co/edit/Dj9Mukig8PAHUYinsapJ?p=preview
Related
I am attempting to use the PolyLabel library with GeoJSON data and the Google Maps API to generate appropriately placed labels for irregular polygons. The documentation says that the library accepts polygon coordinates in GeoJSON-like format.
The problem is that I cannot figure out what data to pass from the Google Maps API data layer to PolyLabel to get the best fit label position.
polygons.forEach(function (feature) {
var geo = feature.getGeometry();
var position = polylabel(???, 1.0);
var mapLabel = new MapLabel({
position: position,
text: feature.getProperty("LABEL"),
fontSize: 25,
fontColor: "red",
map: map
})
currentLabels.push(mapLabel);
});
I have tried multiple variations on passing in the feature, the geometry, the raw coordinates, and constructing polygons from the coordinates.
It is also worth noting that the GeoJSON data contains a mixture of Polygons and MultiPolygons.
Thank you.
definitely difficult to see, but you can find it here.
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/polylabel/index.d.ts
for each point in the polygon, you have [x, y].
Each polygon is then [[x,y]...], and polylabel takes array of polygons.
Similar to the problem found in this question
How to convert OpenLayers polygon coordinates into latitude and longitude?
I have setup a basic map to capture a user defined polygon and convert it to GeoJSON, whilst I'm able to do this with its native projection (ESPG:3857) I would like to take the captured GeoJSON and convert it to EPSG:4326 - which I will then save away. Using the above method of capturing the feature on the drawend event and performing a transform however removes the polygon as the new co-ordinates are not represented in the projection of the map any longer. I am unable to figure out how to to save the GeoJSON in the format I need without deleting the existing polygon
I have tried performing this by using getFeatures on the vector source of the polygon and then performing a transform from the projection i'm using to the projection I want, but this still returns the same coords, I have also (like the linked article) tried using the the writeFeatureObject but it still saves incorrectly
https://jsfiddle.net/20gxo3nt/
dragBox.on('drawend', function(evt){
/* geom = evt.feature.getGeometry().transform('EPSG:3857', 'EPSG:4326');
console.log(geom.getCoordinates()); */
});
$( "#save" ).click(function() {
var geom=vectorSource.getFeatures();
console.log(geom);
var writer=new ol.format.GeoJSON();
var geoJsonStr = writer.writeFeatures(geom);
console.log (geom.proj.transform('EPSG:3857', 'EPSG:4326'));
/* console.log(geoJsonStr) */
});
Uncommenting the code on the drawend event will correctly console.log the co-ordinates,as well as demonstrate polygon disappearing
To get a new geojson
var geom = [];
vectorSource.forEachFeature( function(feature) { geom.push(new ol.Feature(feature.getGeometry().clone().transform('EPSG:3857', 'EPSG:4326'))); } );
var writer = new ol.format.GeoJSON();
var geoJsonStr = writer.writeFeatures(geom);
console.log(geoJsonStr);
Openlayers 6, no need to loop on features
var format = new ol.format["GeoJSON"]();
var geoJsonStr = format.writeFeatures(vectorSource.getFeatures(), { dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857'});
When using JS ArcGis API, is it possible to create a point in ArcGis from lat and long like this
var testPoint = new Point(-98, 38);
or this
var testPoint = new Point(-98, 38, new SpatialReference({ wkid: 4326 }));
and convert it to a different SR so that its x and y are changed automatically? E.g. to wkid 102000/3857?
CONTEXT: (Maybe you can find a workaround)
I'm using heatmap.js to draw heatmapLayers on ArcGis maps. I found some examples and the way this API ingests data is using a variable data on the following format:
var data = [
{
attributes: {},
geometry: {
spatialReference: { wkid: ****},
type: "point",
x: -40,
y: 50
}
},
{another point....}
];
The API itself does some parsing over data variable and then uses this method
screenGeometry = esri.geometry.toScreenGeometry(this._map.extent, this._map.width, this._map.height, parsedData.data[xParsed][yParsed].dataPoint);
to transform the parsed point (parsedData.data[xParsed][yParsed].dataPoint) before finally drawing heatmap.
The main problem is that no matter what wkid I pass to the point (**** in the code before), it interprets it as wkid: 102000, that's why I wanted to do coordinate conversion myself beforehand.
I guess it should be esri.geometry.toScreenGeometry task to actually do that conversion, but, as I said, it ignores the wkid.
Thanks before hand,
esri.geometry.toScreenGeometry is not what you're looking for - that converts the supplied geometry into screen coordinates (ie. pixels), which you would presumably use if you were trying to do custom overlays on the map, or control HTML elements overlapping the map itself.
The function you want is esri.geometry.webMercatorUtils.geographicToWebMercator, which takes in a geometry in lat/long and returns it in 102100 (or 3857) specifically so it can be added to a standard ESRI JS map. From the docco:
require([
"esri/geometry/webMercatorUtils", ...
], function(webMercatorUtils, ... ) {
var geom = webMercatorUtils.geographicToWebMercator(candidate.location);
...
});
(Amusingly, this is the opposite to most coordinate system questions on SO, where people ask "why doesn't my point appear on the map" when they feed in lat/long coordinates. Kudos for working out why it doesn't appear. :) )
I am getting line latitude & longitude as
LINESTRING(1491215.4689647 6893983.2031826,1494163.0718675 6894785.7919795)
after seeing this solution.
how to get points return from OpenLayers.Control.DrawFeature
Now what I want to do is that I want to display start point & end point on my web page.
So how can I extract latitude & longitude from here so that I can show it in my page.
If your linestring is already in OpenLayers, there is no reason to convert it to WKT. Linestring geometry contains array of Points. You can access components of geometry in several ways, for example:
drawControls[key].events.register('featureadded', drawControls[key], function(f) {
// First point
var firstPointGeom = f.feature.geometry.components[0].clone();
// Last point
var secondPointGeom = f.feature.geometry.components[f.feature.geometry.components.length - 1].clone();
// Now you got geometries, let's create features from them...
var firstPointFeat = new OpenLayers.Feature.Vector(firstPointGeom);
var secondPointGeom = new OpenLayers.Feature.Vector(secondPointGeom);
yourVectorLayer.addFeatures([firstPointFeat, secondPointGeom]);
});
Pay attention - this works with LineStrings. Probably it's not necessary to go into detail about clone(), it's up to particular use case, whether you need it, or you can use just var firstPointGeom = f.feature.geometry.components[0];
Thats WKT format, you're looking at. You'll potentially need to reproject those coordinates to the target projection if they are not in the same projection. After than, you should be able ot ask openlayers for the points of any given geometry using the base geometry functionaily. Get the point array from the linestring instance and iterate over it. Make sure you know the right coordinate order for your projection / data model.
Hope that helps!
i need some help with google map api v3 markers.
I got an array which contains coordinates i retrieve from a file. I am trying to traverse the array, and plot them using the markers.
Traversing the array to retrieve the coordinates is not a problem, however, when i start using the coordinates to plot on google map. i realise that i am getting (NaN, NaN) as the coordinates.. Because of this, i am not able to do the plotting.. any idea why isit? Thanksss
my codes so far:
var temp = new google.maps.LatLng(myObject[o]);
retrieverouteMarker(temp);
The constructor for LatLng takes two arguments (the latitude and longitude of the point), so this line is clearly wrong:
var temp = new google.maps.LatLng(myObject[o]);
Of course, since we have to idea what myObject is, or what the function retrieverouteMarker does, there isn't much more we can do to help.