How to go to extent programmatically? - openlayers-5

I am new to Openlayers 5 and I want to move the map to a specific extent programmatically.
I tried
var bbox = [485319.36436093575, 5749497.169086075, 498451.8156390643, 5758869.310913925];
map.getView().fit(bbox, {size: map.getSize()});
but nothing happens.
What am I doing wrong? Is there another method I should use?
I didn't find anything in the API docs.

It's working here.
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [raster],
target: 'map',
view: new ol.View()
});
var bbox = [485319.36436093575, 5749497.169086075, 498451.8156390643, 5758869.310913925];
map.getView().fit(bbox, {size: map.getSize()});
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>

Related

Embedding an OpenLayers slippy map into Sphinx reStructuredText page

I want to embed a slippy map into my sphinx page.
I'm trying this simple example: https://wiki.openstreetmap.org/wiki/OpenLayers_Marker_Example
So my rst document is:
.. raw:: html
<body>
<div id="mapdiv"></div>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script>
map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
var lonLat = new OpenLayers.LonLat( -0.1279688 ,51.5077286 )
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
map.getProjectionObject() // to Spherical Mercator Projection
);
var zoom=16;
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(lonLat));
map.setCenter (lonLat, zoom);
</script>
</body>
But nothing appears on the page.
I have tried and failed trying to use other javascript mapping api's such as leaflet but with no luck. I'm new to using sphinx/reStructuredText so maybe there's something obivous I am missing?
<body> already exists on your page, so you need to remove it from your rst.
You also need to specify height and width for the mapdiv element, for instance, something like this:
.. raw:: html
<div id="mapdiv" style="height: 200px; width: 100%"></div>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script>
map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
var lonLat = new OpenLayers.LonLat( -0.1279688 ,51.5077286 )
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
map.getProjectionObject() // to Spherical Mercator Projection
);
var zoom=16;
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(lonLat));
map.setCenter (lonLat, zoom);
</script>
#anatoly answer is correct but there was also another step.
I also had a Blocked loading mixed active content error found when checking the developer tools (thanks #giacomo for pointing me towards this), leading to this answer thread: Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox? which tells me that the cause is http protocol not being secure. The protocol can be removed altogether.
So the final code is:
.. raw:: html
<div id="mapdiv" style="height: 200px; width: 100%"></div>
<script src="//openlayers.org/api/OpenLayers.js"></script>
<script>
map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
var lonLat = new OpenLayers.LonLat( -0.1279688 ,51.5077286 )
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
map.getProjectionObject() // to Spherical Mercator Projection
);
var zoom=16;
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(lonLat));
map.setCenter (lonLat, zoom);
</script>

How to draw a polyline with initial point in Leaflet

I'm using custom polyline drawer from Leaflet.draw
let polylineDrawer = new L.Draw.Polyline(map, {})
polylineDrawer.enable()
I need to programmatically add starting point to polyline
I've tried calling addVertex of L.Draw.Polyline. Looks like it's doesn't work with custom polyline drawer cause of addHooks or something... Tried to change sources, no results.
Also tried firing click on map after drawer is enabled. Like so:
let point = new L.LatLng(x, y)
map.fireEvent('click', {
latlng: point,
layerPoint: map.latLngToLayerPoint(point),
containerPoint: map.latLngToContainerPoint(point),
})
Also doesn't work
EDIT: Actually, AddVertex does work with custom polylines. It "didn't work" because I passed wrong arguments in my function. Somehow, I missed that.
Using addVertex on your drawer object does let you add a starting point to your line :
var polylineDrawer = new L.Draw.Polyline(map, {})
polylineDrawer.enable();
var latlng = L.latLng(48.8583736, 2.2922926);
polylineDrawer.addVertex(latlng);
and a demo
var style = {
stroke: true,
color: 'red',
weight: 4,
opacity: 0.5
};
var map = L.map(document.getElementById('map')).setView([48.8583736, 2.2922926], 15);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var drawnItems = new L.geoJson(null, {style: style}).addTo(map);
map.on(L.Draw.Event.CREATED, function (event) {
var layer = event.layer;
drawnItems.addLayer(layer);
});
var polylineDrawer = new L.Draw.Polyline(map, {})
polylineDrawer.enable();
var latlng = L.latLng(48.8583736, 2.2922926);
polylineDrawer.addVertex(latlng);
html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.12/leaflet.draw.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.12/leaflet.draw.js"></script>
<div id='map'></div>

custom heatmap leaflet plugin

in index.html I woluld like to add two Heatmaps users can see by checkbox in menu top right corner.
menu show other stuff by code like this
layerControl.addOverlay(geojson, "H2OpenMap");
in this portion of the page (line 383 to line 397)
$.getJSON('api.php', {'wells': '1'}, function(remoteData){
var geojson = L.geoJson(remoteData, {
pointToLayer: function (feature, latlng) {
var icon = chooseIcon(feature['properties']);
var marker = L.marker(latlng, {icon: new h2icon( {iconUrl: icon} )} );
var markerText = buildPopup(feature, true, latlng);
marker.bindPopup(markerText);
return marker;
}
}).addTo(map);
layerControl.addOverlay(geojson, "H2OpenMap");
map.fitBounds(geojson.getBounds(), {'padding': [10,10]});
});
First heat should use data from the same code before, selected by
if(feature['drinking_water'] == 'yes' ) {...
}
Second heat should use data from the same code before, selected by
if(feature['drinking_water'] == 'no' ) {...
}
The goal is to have two heat maps, one for clean water resources the other for not clean water resources, both can be selected by ratio button.
I've find this code looks good but I'm not able to give him data to use to create heatmap.....
//--------------------https://www.patrick-wied.at/static/heatmapjs/plugin-leaflet-layer.html-----------//
$.getJSON('api.php', {'wells': '1'}, function(remoteData){
var geojson = L.geoJson(remoteData, {
pointToLayer: function (feature, latlng) {
var heatData = L.marker(latlng);
console.log(heatData);
//var heatData = L.marker([{lat: new latlng(lat), lng: new latlng(lng)}]);
}})});
/*var testData = {
max: 8,
data: [{lat: 24.6408, lng:46.7728, count: 3},{lat: 50.75, lng:-1.55, count: 1}, ...]
};*/
var cleanWater = heatData;// mettere in un array solo la posizione degli elementi che rispettano la seguente condizione: feature['drinking_water'] == 'yes'
var cfg = {
// radius should be small ONLY if scaleRadius is true (or small radius is intended)
// if scaleRadius is false it will be the constant radius used in pixels
"radius": 2,
"maxOpacity": .8,
// scales the radius based on map zoom
"scaleRadius": true,
// if set to false the heatmap uses the global maximum for colorization
// if activated: uses the data maximum within the current map boundaries
// (there will always be a red spot with useLocalExtremas true)
"useLocalExtrema": true,
// which field name in your data represents the latitude - default "lat"
latField: 'lat',
// which field name in your data represents the longitude - default "lng"
lngField: 'lng',
// which field name in your data represents the data value - default "value"
valueField: 'count'
};
var heatmapLayer = new HeatmapOverlay(cfg);
var map = new L.Map('map-canvas', {
center: new L.LatLng(25.6586, -80.3568),
zoom: 4,
layers: [baseLayer, heatmapLayer]
});
heatmapLayer.setData(cleanWater);
//------------------------//--------------------//--------------------//--------------------//--------------------*/
in the root project it's following file with complete code:
https://github.com/H2OpenMap/map/blob/master/index_heat_test.html
Simplifying your problem I try to suggest you this example ...
http://bl.ocks.org/d3noob/raw/8973028/
This a simple code that implements a Leaflet heat map.
If you see at the source code ...
<!DOCTYPE html>
<html>
<head>
<title>Simple Leaflet Map with Heatmap </title>
<meta charset="utf-8" />
<link
rel="stylesheet"
href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"
/>
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>
<script
src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js">
</script>
<script
src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js">
</script>
<script src="2013-earthquake.js"></script>
<script>
var map = L.map('map').setView([-41.5546,174.146], 10);
mapLink =
'OpenStreetMap';
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© ' + mapLink + ' Contributors',
maxZoom: 18,
}).addTo(map);
var heat = L.heatLayer(quakePoints,{
radius: 20,
blur: 15,
maxZoom: 17,
}).addTo(map);
</script>
</body>
.... you'll find that the data is simulated with a coordinate array that you can see here ...
http://bl.ocks.org/d3noob/raw/8973028/2013-earthquake.js
I think that you've to convert your geojson data in this format and all will work!
Cesare

Mapbox non-geographic

I'm trying to mixed up for at least a week , mapbox with leaflet to did a Non geographic map.
My first step was to build it with maptiler.com which generated with the tiled a code based on leaflet. But i want to add to this code a Geojson proprites.
I saw that in Mapbox there is already a geojson popup built-in.
This is why i want to use my leaflet map code + mapbox popup, it's possible ?
Thanks,
Jade
<!DOCTYPE html>
<html>
<head>
<title>map</title>
<meta charset="utf-8"/>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js'></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css' rel='stylesheet' />
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.ie.css" />
<![endif]-->
<script>
L.mapbox.accessToken = 'pk.eyJ1IjoiamFkZTIyOTMiLCJhIjoiRDdweEFrZyJ9.Yk4XeNmp3SExkU41Z7BU3w';
function init() {
var mapMinZoom = 3;
var mapMaxZoom = 6;
var map = L.map('map', {
maxZoom: mapMaxZoom,
minZoom: mapMinZoom,
crs: L.CRS.Simple
}).setView([0, 0], mapMaxZoom);
var mapBounds = new L.LatLngBounds(
map.unproject([0, 7680], mapMaxZoom),
map.unproject([10496, 0], mapMaxZoom));
map.fitBounds(mapBounds);
L.tileLayer('{z}/{x}/{y}.png', {
minZoom: mapMinZoom, maxZoom: mapMaxZoom,
bounds: mapBounds,
noWrap: true
}).addTo(map);
// The GeoJSON representing a point feature with a property of 'video' for the Vimeo iframe
var geoJson = {
features: [{
type: 'Feature',
properties: {
'marker-color': '#f00',
'marker-size': 'large',
'marker-symbol': 'rocket',
video: '<iframe src="//player.vimeo.com/video/106112939" width="380" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> <p><h2>How Simplicity Will Save GIS</h2><p>Vladimir Agafonkin from FOSS4G on Vimeo.</p>',
},
geometry: {
type: 'Point',
coordinates: [0,0]
}
}]
};
var myLayer = L.mapbox.featureLayer().addTo(map);
// Add the iframe in a marker tooltip using the custom feature properties
myLayer.on('layeradd', function(e) {
var marker = e.layer,
feature = marker.feature;
// Create custom popup content from the GeoJSON property 'video'
var popupContent = feature.properties.video;
// bind the popup to the marker http://leafletjs.com/reference.html#popup
marker.bindPopup(popupContent,{
closeButton: false,
minWidth: 320
});
});
// Add features to the map
myLayer.setGeoJSON(geoJson);
}
</script>
<style>
html, body, #map { width:100%; height:100%; margin:0; padding:0; }
background-color:white;
</style>
</head>
<body onload="init()">
<div id="map"></div>
</body>
</html>
It seems that you're asking 2 separate questions here. The original question about non-geographic maps and your follow-up question about adding an iframe to a leaflet popup. I'll try to address your follow-up question:
Let's take the Mapbox example you linked (https://www.mapbox.com/mapbox.js/example/v1.0.0/video/) and adapt it to work with the video you would like to display.
If you've already got some GeoJSON data, you can edit it to include a video property. Let's look at the GeoJSON code from the Mapbox example:
var geoJson = {
features: [{
type: 'Feature',
properties: {
'marker-color': '#f00',
'marker-size': 'large',
'marker-symbol': 'rocket',
video: '<iframe src="//player.vimeo.com/video/106112939" width="380" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> <p><h2>How Simplicity Will Save GIS</h2><p>Vladimir Agafonkin from FOSS4G on Vimeo.</p>',
},
geometry: {
type: 'Point',
coordinates: [0,0]
}
}]
};
See that video property? Its value contains the iframe code that will end up inside the popup for the map marker it corresponds to. I went ahead and added the iframe code from your YouTube video to the above example and you can see it in action on jsfiddle here: http://jsfiddle.net/danswick/tcxvpw84/.
Your GeoJSON data probably doesn't have a video property, but you can add it using a text editor or geojson.io.
Further down in our example code, we access that video property, set it to a variable, and bind it to our marker's popup:
// Create custom popup content from the GeoJSON property 'video'
var popupContent = feature.properties.video;
// bind the popup to the marker http://leafletjs.com/reference.html#popup
marker.bindPopup(popupContent,{
closeButton: false,
minWidth: 320
});
Mapbox just uses Leaflet's bindPopup method which comes standard with L.Marker. If you create a L.GeoJSON layer, you can add a popup to each feature using the onEachFeature option of L.GeoJSON which takes a function with two parameters: feature and layer. In there you can bind a popup to your feature:
For example when you have features like this one, with a property called name:
{
"type": "Feature",
"properties": {
"name": "E"
},
"geometry": {
"type": "Point",
"coordinates": [0, 0]
}
}
You could then use that name value when binding a popup to your feature like this:
// Create new GeoJSON layer
L.geoJson(data, {
// Define the onEachFeature function which runs on every feature
onEachFeature: function (feature, layer) {
// Bind a popup to the layer using the name property
layer.bindPopup(feature.properties.name);
}
}).addTo(map);
Here's a working example on Plunker: http://plnkr.co/edit/iPLHqi?p=preview
Thanks, to take time to reply.
But actually i wanted to use geojson just to put iframe in a leaflet popup.
like this :
L.marker(map.unproject([452, 410])).addTo(map).bindPopup("<iframe width="560" height="315" src="https://www.youtube.com/embed/zP71_cXfiu0" frameborder="0" allowfullscreen></iframe>");
But it doesn't work but with the same syntax this work : I just saw in this exemple that with geojson it's might work :
https://www.mapbox.com/mapbox.js/example/v1.0.0/video/
L.marker(map.unproject([452, 410])).addTo(map).bindPopup("https://www.youtube.com/embed/zP71_cXfiu0");
Sorry if i'm a little bit confusing, because i'm designer and all this "code thing" it's new for me :)

Getting mapQuest error: map.addControl is not a function

I've loaded the MapQuest JavaScript api module and am able to bring in the basic sample map at http://developer.mapquest.com/web/documentation/sdk/javascript/v7.0/basic-map but when I try to add map controls using their next example I get the JavaScript error:
map.addControl is not a function
I tried window.map.addControl but that generates the same error.
Does anyone know what might be wrong?
Thanks
You need to add the map control code within your MQA.EventUtil.observe
right after your call to window.map = new MQA.TileMap(options);
Code:
<html>
<head>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?key=Kmjtd%7Cluua2qu7n9%2C7a%3Do5-lzbgq"></script>
<script type="text/javascript">
MQA.EventUtil.observe(window, 'load', function() {
/*Create an object for options*/
var options={
elt:document.getElementById('map'), /*ID of element on the page where you want the map added*/
zoom:10, /*initial zoom level of map*/
latLng:{lat:39.743943, lng:-105.020089}, /*center of map in latitude/longitude*/
mtype:'map' /*map type (map)*/
};
/*Construct an instance of MQA.TileMap with the options object*/
window.map = new MQA.TileMap(options);
MQA.withModule('largezoom','traffictoggle','viewoptions','mousewheel', function() {
map.addControl(
new MQA.LargeZoom(),
new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5,5))
);
map.addControl(new MQA.TrafficToggle());
map.addControl(new MQA.ViewOptions());
map.enableMouseWheelZoom();
});
});
</script>
</head>
<body>
<div id='map' style='width:750px; height:280px;'></div>
</body>
</html>
try like this map.current.addControl
Make sure you add the module for the control before adding the control to the map.