Fitting map bounds to raster layer - javascript

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

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

Capture window Lat, Longs with Leaflet

I am trying to figure out how to capture the four corners of a Leaflet window, so that I might load points based on where a user is zoomed in geographically. For example, have a look here.
Now, how would I capture the four corners of that view so that I could load only the points that are geometrically bounded to that general location - downtown London?
I have not been able to find any example for Leaflet specifically. Any assistance will be appreciated.
The term you should be searching with is called "bounds". Leaflet's L.Map has a method called getBounds which will return the bounds of the current mapview:
http://leafletjs.com/reference.html#map-getbounds
Returns the LatLngBounds of the current map view.
It returns a LatLngBounds object which consist of a southwest and a northeast LatLng object:
http://leafletjs.com/reference.html#latlngbounds
Represents a rectangular geographical area on a map.
How you use those bounds to query your points of interest from your server depends on the platform you are working with.
If you already have a dataset loaded and you want filter that based on the current bounds you could use contains method of the LatLngBounds object. You can use that to check if a point is contained within the current bounds:
http://leafletjs.com/reference.html#latlngbounds-contains
Returns true if the rectangle contains the given point.

Google Maps API v3 -- How to convert .getBounds() to to pixel coordinates?

I know how to use an overlay projection to get a LatLng object, and then convert that single LatLng to pixels, using .fromLatLngToDivPixel()
However, .getBounds() returns a pair of LatLng coordinates. I've tried accessing it like it's an array (as in specifying index[1] for example) but that does not work. It doesn't seem to be an array.
Is there a way to convert the value from .getBounds() to pixel data?
However, .getBounds() returns a pair of LatLng coordinates. I've tried
accessing it like it's an array (as in specifying index1 for
example) but that does not work. It doesn't seem to be an array.
LatLngBounds is not an array, it's an object and the documentation shows you two methods to get the coordinates:
var NE = bounds.getNorthEast();
var SW = bounds.getSouthWest();
Those two methods return LatLng objects which you can pass to fromLatLngToDivPixel()
However, if you got your LatLngBounds object by reading map.getBounds() then you already know what the pixel values should be, (the corners of your map container DIV).

OpenLayers LonLat transform

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.

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