OpenLayers LonLat transform - javascript

I want to use decimal Lon and Lat like Google Maps uses. But it seems I need to transform the LonLat object in OpenLayers, e.g.
var map, layer;
function init(){
map = new OpenLayers.Map('map');
layer = new OpenLayers.Layer.OSM( "Simple OSM Map");
map.addLayer(layer);
map.setCenter(
new OpenLayers.LonLat(-1.60400390625, 54.07228265560386).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
), 6
);
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(0,0);
var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png', size, offset);
markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(-1.60400390625, 54.07228265560386).transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()),icon));
}
Each time I place a marker the position needs to be transformed to EPSG:4326. Is there a way to tell the map to always use this projection?

Whether you can set the projection on a map or not, depends on which service you are using for the base layer. As far as I know, OSM only provides its rendered tiles in EPSG:900913, so there is no way around transforming your coordinates before adding them to the map. You could search for a service that provides its tiles in multiple projections, but I haven't seen one that is free to use so far. An alternative would be to render your own tiles in the needed projection and provide them through your own tile server.
Let's suppose you have such a map, you can change the projection using OpenLayers.Map.setOptions() like this:
map.setOptions({
projection: "EPSG:4326"
});
But you may also need to set some projection related properties, like maxExtent etc. See this question.

Related

Converting OpenLayers Polygon to GeoJSON with different projection

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'});

Fitting map bounds to raster layer

I've ran across all fitbounds tutorials for Mapbox and still cannot figure out how refocus my map on a given raster layer. I have a menu that toggles a number of older maps and would like to refit the map at each turn.
Here's what I have so far. mapnumber is the string for my raster map.
var coordinates = map.getBounds(mapnumber);
var bounds = new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]);
map.fitBounds({bounds});
The bounds are there, I just cannot use fitbounds on them. This is the error.
lng_lat.js:97 Uncaught Error: `LngLatLike` argument must be specified
as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array
of [<lng>, <lat>]
Uncaught Error: LngLatLike argument must be specified
as a LngLat instance
It looks like you're using mapboxgl.LngLatBounds incorrectly. You'll need to pass in two LngLat instances, rather than two coordinates. The API docs have an example that creates a point for the southwest and northeast corners of your bounding box:
var sw = new mapboxgl.LngLat(-73.9876, 40.7661);
var ne = new mapboxgl.LngLat(-73.9397, 40.8002);
var llb = new mapboxgl.LngLatBounds(sw, ne);
Then you can use map.fitBounds() with the bounding box
map.fitBounds(llb);
UPDATE: answering follow up question
how can I extract the two sets (sw and ne) from the raster?
You can use the map.getSource() method. Pass in the source ID of your raster layer and that will return an object that has a bounds property. Use this bounds property to pass into map.fitBounds().
var bounds = map.getSource('mapbox://username.source-id').bounds;
map.fitBounds(bounds);
Here's a working example: https://codepen.io/mapsam/pen/RZvyBQ

Google maps LatLng and LatLngBounds returning different results

I'm currently learning to use google maps and am following the following to set a max bound for my map: Google Maps v3 - limit viewable area and zoom level
My bounds are set as:
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(41.600, -87.857),
new google.maps.LatLng(42.065, -87.310)
)
Within my dragend event listener, I console.log(strictBounds) and am getting the following:
It is returning my south-west Latitude and north-east Latitude together as one LatLng and my south-west Longitude and north-east Longitude as one LatLng.
I could sorta hack it and set south-west and north-east coordinates so that the return would be what I want it to be, but I was wondering why this is happening in this scenario and would I be running into this problem further with other google map methods?
EDIT:
Just to clarify, my two LatLng positions set in strictBounds should be my southWest and northEast positions for the max bounds of the map.
When I use the addListener method provided in the link above (Google Maps v3 - limit viewable area and zoom level), it grabs the wrong lat/long from strictBounds.
Instead of grabbing:
(41.6, -87.857), (42.065, -87.310)
It grabs:
(41.6, 42.065), (-87.31, -87.856999..)
The way you define the bound is correct. Just don't use console.log(strictBounds). Use the following instead
var sw = strictBounds.getSouthWest();
var ne = strictBounds.getNorthEast();
console.log(sw.lat() + "," + sw.lng());
console.log(ne.lat() + "," + ne.lng());

How can I use part of a larger image as a marker in OpenLayers?

Is it possible to use part of a larger image as a marker with OpenLayers?
Like this (in google maps):
var icon = new google.maps.MarkerImage(
"img/marker_sprite.png",
new google.maps.Size(26, 44),
new google.maps.Point(0, 44)
);
The basic recipe for adding a marker to a map in OpenLayers starts with adding a Marker layer to your map, which you can do like this:
var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
Then you will need to add markers to that layer, which goes something like this:
var position = new OpenLayers.LonLat(longitude, latitude);
position.transform(new OpenLayers.Projection("EPSG:4326",
map.getProjectionObject());
var icon = new OpenLayers.Icon("img/marker_sprite.png",
new OpenLayers.Size(26, 44));
var marker = new OpenLayers.Marker(position, icon);
markers.addMarker(marker);
Unfortunately it's not possible, as far as I know, so set the origin for the marker within the image file so you can just use part of the image. Well you can, but only if the part you want is in the corner, which isn't very helpful.

Openlayers - Projection issues when getting latitude/longitude from a point

I'm trying to get the latitude/longitude from a draggable marker with Openlayers and OSM but I can't find the good settings for the projection conversion, what I am doing wrong ?
Here is the code: http://pastie.org/2300321 (see addMarker l140 & updateTargets l153) & and a little demo test.
If you submit an address, then drag the marker, the longitude and latitude are wrong. I tested a few different projections but I'm not sure what I've to useā€¦
I think the problem is inside updateTargets method:
var point = this.feature.geometry;
var pixel = new OpenLayers.Pixel(point.x, point.y);
var coord = this.map.getLonLatFromPixel(pixel).transform(
new OpenLayers.Projection("EPSG:900913"),
new OpenLayers.Projection("EPSG:4326")
);
this.feature.geometry is already specified in lon/lat coordinates, not in pixels. So I suggest that you skip second line and do the conversion from OpenStreetMap projection to lon/lat directly on geometry object:
var coord = this.feature.geometry.transform(
new OpenLayers.Projection("EPSG:900913"),
new OpenLayers.Projection("EPSG:4326")
);

Categories

Resources