OpenLayers map doesn't get loaded correctly - javascript

I'm making an ASP.NET site with an OpenLayers map, but in IE it is always loading and in Chrome it says, that the site doesn't react, after a while.
The Script is inside a content tag.And I'm using release 2.13.1.
This is the code:
<script type="text/javascript" src="../Scripts/OpenLayers.js" ></script>
<script type="text/javascript" src="../Scripts/expand.js"></script>
<!-- map built with OpenLayers api on OpenStreetMap -->
<script type="text/javascript">
map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
epsg4326 = new OpenLayers.Projection("EPSG:4326"); // WGS 1984 projection
projectTo = map.getProjectionObject(); // The map projection (Spherical Mercator)
// Define center-point
var lonLat = new OpenLayers.LonLat(8.2891666666666666666666666, 46.8344444444444444444).transform(epsg4326, projectTo);
map.setCenter(lonLat, 8);
</script>
Is my link wrong or did I forget something else?

You're using OpenLayers 2 syntax with the OpenLayers 3 library. One key difference is rather than saying
map = new OpenLayers.Map("mapdiv");
You want to use
var map = new ol.Map("mapdiv");
You'll need to correct the other instances where you use 'OpenLayers' instead of 'ol'.
Here's a link to the getting started with OpenLayers 3 documentation.

Try this will work
<html>
<head>
<title>OpenLayers Demo</title>
<style type="text/css">
html,body,#mapdiv {
width: 100%;
height: 100%;
margin: 0;
}
</style>
<script src="../js/OpenLayers.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="../css/ol-theme-style.css" />
</head>
<body>
<div id="mapdiv"></div>
<script>
map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
epsg4326 = new OpenLayers.Projection("EPSG:4326"); //WGS 1984 projection
projectTo = map.getProjectionObject(); //The map projection (Spherical Mercator)
var lonLat = new OpenLayers.LonLat(73.8567, 18.5203).transform(epsg4326, projectTo);
var zoom = 14;
map.setCenter(lonLat, zoom);
</script>
</body>
</html>

Related

Noise Points disappearing at certain zoom level. [HERE Maps API for Javascrip]

First of all, let's clarify the problem:
I have a map that shows a cluster of points
Marker Cluster Image1
When I start zooming one of the points, everything work as expected to a level of zoom over 5 km Marker Cluster Image2
When the zoom level increases to less than 5 km, the NoisePoint disappears. Marker Cluster Image3
If I keep zooming where the NoisePoint should be, after a certain level, in this case less than 100 meters, the NoisePoint is displayed again. Marker Cluster Image4
How it is built:
I have a function that takes as an argument array of objects containing lat and lng
showTruckPosition(truckDataPositionCordArray) {
var dataPoints = [];
dataPoints = truckDataPositionCordArray.map((item) => {
return new H.clustering.DataPoint(item.lat, item.lng);
});
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
// min: 1,
// max: 20,
clusteringOptions: {
eps: 32,
minWeight: 2
}
});
let layer = new H.map.layer.ObjectLayer(clusteredDataProvider);
this.map.addLayer(layer);
}
Min and Max options on H.clustering.Provider do not change this strange behavior.
How to stop dies behavior? I need the Noise Points to be visible at max Zoom too.
Please check the below example.
/**
* Display clustered markers on a map
*
* Note that the maps clustering module https://js.api.here.com/v3/3.1/mapsjs-clustering.js
* must be loaded to use the Clustering
* #param {H.Map} map A HERE Map instance within the application
* #param {Object[]} data Raw data that contains airports' coordinates
*/
function startClustering(map, data) {
// First we need to create an array of DataPoint objects,
// for the ClusterProvider
var dataPoints = data.map(function (item) {
return new H.clustering.DataPoint(item.latitude, item.longitude);
});
// Create a clustering provider with custom options for clusterizing the input
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {
// Maximum radius of the neighbourhood
eps: 32,
// minimum weight of points required to form a cluster
minWeight: 2
}
});
// Create a layer tha will consume objects from our clustering provider
var clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
// To make objects from clustering provder visible,
// we need to add our layer to the map
map.addLayer(clusteringLayer);
}
/**
* Boilerplate map initialization code starts below:
*/
// Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
// Step 2: initialize a map
var map = new H.Map(document.getElementById('map'), defaultLayers.vector.normal.map, {
center: new H.geo.Point(30.789, 33.790),
zoom: 2,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
// Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: create the default UI component, for displaying bubbles
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Step 5: cluster data about airports's coordinates
// airports variable was injected at the page load
startClustering(map, airports);
#map {
width: 95%;
height: 450px;
background: grey;
}
#panel {
width: 100%;
height: 400px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Marker Clustering</title>
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="../template.css" />
<script type="text/javascript" src='../test-credentials.js'></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-clustering.js"></script>
<script type="text/javascript" src="./data/airports.js"></script>
</head>
<body id="markers-on-the-map">
<div class="page-header">
<h1>Marker Clustering</h1>
<p>Cluster multiple markers together to better visualize the data</p>
</div>
<p>This example displays a map showing the distribution of
airports across the world. The locations were obtained by using
the OpenFlights Airport Database.
Instead of adding a marker for each location, the data has been clustered,
and individual airports are only shown at higher zoom levels.</p>
<div id="map"></div>
<h3>Code</h3>
<p>Marker clustering requires the presence of the <code>mapsjs-clustering</code> module of the API.
The <code>H.clustering.Provider</code> class is used to load in data points and prepare them for clustering.
The result is added to the map as an additional layer using the <code>map.addLayer()</code> method.</p>
<script type="text/javascript" src='demo.js'></script>
</body>
</html>
For more details please refer below exmaple.
https://jsfiddle.net/gh/get/jquery/2.1.0/heremaps/maps-api-for-javascript-examples/tree/master/marker-clustering

How to write correct HERE javascript source in html head? Browser always fails to load resource

I just want to create a default website, showing a map like this demo from HEREMaps. The HTML and JavaScript code is already provided, so I just had to put both together and should work, but it seems like there is a mistake.
Unfortunately, my code fails in every browser, because there is no content behind some links to script resources in the HTML head:
../template.css
../test-credentials.js
../js-examples-rendering-helpers/iframe-height.js
This seems obvious to me, but somehow jsFiddle can read this file without any problem and I am quite sure that HEREMaps doesn't provide wrong code, so I would like to know what is wrong with my code.
For safety reasons, I am not going to write my credentials, so window.apikey has to be replaced, if you try it out.
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Map at a specified location</title>
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="../template.css" />
<script type="text/javascript" src='../test-credentials.js'></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>
<script type="text/javascript" src='../js-examples-rendering-helpers/iframe-height.js'></script>
</head>
<body id="markers-on-the-map">
<script type="text/javascript" src='demo.js'>
/**
* Moves the map to display over Berlin
*
* #param {H.Map} map A HERE Map instance within the application
*/
function moveMapToBerlin(map){
map.setCenter({lat:52.5159, lng:13.3777});
map.setZoom(14);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Europe
var map = new H.Map(document.getElementById('map'),
defaultLayers.vector.normal.map,{
center: {lat:50, lng:5},
zoom: 4,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Now use the map as required...
window.onload = function () {
moveMapToBerlin(map);
}
</script>
</body>
</html>
Following the link you provided. I've set up a working example:
// HEREMaps - Demo API Key. You should change this.
var apikey = 'H6XyiCT0w1t9GgTjqhRXxDMrVj9h78ya3NuxlwM7XUs';
/**
* Moves the map to display over Berlin
*
* #param {H.Map} map A HERE Map instance within the application
*/
function moveMapToBerlin(map) {
map.setCenter({
lat: 52.5159,
lng: 13.3777
});
map.setZoom(14);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: apikey
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Europe
var map = new H.Map(document.getElementById('map'),
defaultLayers.vector.normal.map, {
center: {
lat: 50,
lng: 5
},
zoom: 4,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
window.addEventListener('resize', () => map.getViewPort().resize());
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Now use the map as required...
window.onload = function() {
moveMapToBerlin(map);
}
#map {
width: 95%;
height: 450px;
background: grey;
}
#panel {
width: 100%;
height: 400px;
}
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js" charset="utf-8"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js" charset="utf-8"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js" charset="utf-8"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" charset="utf-8"></script>
<!-- Map Container -->
<div id="map"></div>

Leaflet: Polygon center objects that are useable by MarkerCluster

Is there there a way to add centerpoints created via .getCenter() within an onEachFeature event (see below) to an L.Marker, or similar, object that contains all of the centerpoints created on that event, that can be used by Leaflet.Markercluster?
I thought using featureGroup might be the solution, but apparently not.
I can get unclustered centerpoints show up on the map via the addTo(map) method on L.Marker or L.FeatureGroup, but, unfortunately, when I try to use markerCluster on the objects either of those two create, the the map comes up empty. No error messages are appearing on the console in the brower.
I'm still pretty green at JS, so I have a hunch there's something fundamental I'm missing, perhaps about L.Markercluster itself, and my apologies for any noob errors here.
Libraries:
<!-- Leaflet -->
<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>
<!-- ESRI Leaflet -->
<script src="https://unpkg.com/esri-leaflet#2.0.4/dist/esri-leaflet.js"></script>
<!-- Leaflet-markercluster -->
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster#1.0.6/dist/MarkerCluster.css"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster#1.0.6/dist/MarkerCluster.Default.css"></script>
<script src="https://unpkg.com/leaflet.markercluster#1.0.6/dist/leaflet.markercluster.js"></script>
<!-- Leaflet.MarkerCluster.LayerSupport -->
<script src="https://unpkg.com/leaflet.markercluster.layersupport#1.0.5/dist/leaflet.markercluster.layersupport.js"></script>
Script:
<script>
var map = L.map('map', {
center: [42.389810, -72.524684],
zoom: 5
});
var esriTopo = L.esri.basemapLayer('Topographic').addTo(map);
var ProjectMap = L.esri.featureLayer ({
url: 'https://services.arcgis.com/2gdL2gxYNFY2TOUb/arcgis/rest/services/NECSC_Test_Data/FeatureServer/1',
//cheap hack to making the polygons invisible
weight: 0,
fillOpacity: 0,
// creating the centerpoints
onEachFeature: function(feature,layer){
if (feature.geometry.type = 'Polygon') {
var bounds = layer.getBounds();
var center = bounds.getCenter();
var centerpoints = L.marker(center);
centerpointlayer.addLayer(centerpoints);
// centerpointlayer defined below as global variable
};
};
}).addTo(map);
var centerpointlayer = L.featureGroup();
//
var clusters = L.markerClusterGroup.layerSupport();
clusters.addTo(map);
clusters.checkIn(centerpointlayer);
map.zoomIn(5);
map.zoomOut(5);
</script>
</body>
</html>
Gah...Turns out I was implementing L.Markercluster wrong (i.e., not like it says in the API docs). The final lines of code before /script at the end should read:
var centerpointlayer = L.layerGroup();
var clusters = L.markerClusterGroup.layerSupport();
clusters.addLayer(centerpointlayer);
map.addLayer(clusters);

Polygon from LeafletDraw to GeoJSON

This is my first attempt working with javascript and GeoJSON by using leaflet.
So far, I got the desired map and the leaflet.draw plugin working in the way that I can draw a shape and it appears on my screen.
I tried to write this shape to a GeoJSON that I want to use in R.
Therfore I used the ideas presented here to create the GeoJSON string. I think the desired information for me is stored in the variable shape_for_db.
However, using Firebug in Firefox I am not able to find this variable.
Do I get something wrong here?
This is the script I am using:
<html>
<head>
<title>A Leaflet map!</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v1.0.0-rc.1/leaflet.css" />
<link rel="stylesheet" href="http://leaflet.github.io/Leaflet.draw/leaflet.draw.css" />
<script src="http://cdn.leafletjs.com/leaflet/v1.0.0-rc.1/leaflet.js"></script>
<script src="jquery-2.1.1.min.js"></script>
<script src="http://leaflet.github.io/Leaflet.draw/leaflet.draw.js"></script>
<style>
#map{ width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
// base map
var map = L.map('map').setView([51.25,10.57], 8);
// load a tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',
{
attribution: 'Tiles by: OpenStreetMaps',
maxZoom: 17,
minZoom: 5
}).addTo(map);
// Initialise the FeatureGroup to store editable layers
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
drawnItems.addLayer(layer);
});
// Shape to GeoJSON
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var shape = layer.toGeoJSON()
var shape_for_db = JSON.stringify(shape);
});
</script>
</body>
</html>
The scope for your shape_for_db is inside your second listener for draw-created. You can place on window.shape_for_db if you are doing this for a one-off experimental/playing around approach and want to use your dev console/Firebug. Or set up var shape_for_db outside the listener.

How can I get the smallest LatLngBounds that still contains a set of Lat/Long Coordinates in Google Maps JS API?

I need to plot a set of coordinates on the map in response to a user selection, and when it happens, I'd like to pan the map to focus on that set of points. How can I find the smallest bounding box (LatLngBounds) that contains all of the coordinates?
In addition to the Stack Overflow post which #Crescent Fresh pointed to above (which is using the v2 API), the method you'd want to use is the LatLngBounds.extend().
Here's a complete example, using the v3 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps LatLngBounds.extend() Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var markerBounds = new google.maps.LatLngBounds();
var randomPoint, i;
for (i = 0; i < 10; i++) {
// Generate 10 random points within North East America
randomPoint = new google.maps.LatLng( 39.00 + (Math.random() - 0.5) * 20,
-77.00 + (Math.random() - 0.5) * 20);
// Draw a marker for each random point
new google.maps.Marker({
position: randomPoint,
map: map
});
// Extend markerBounds with each random point.
markerBounds.extend(randomPoint);
}
// At the end markerBounds will be the smallest bounding box to contain
// our 10 random points
// Finally we can call the Map.fitBounds() method to set the map to fit
// our markerBounds
map.fitBounds(markerBounds);
</script>
</body>
</html>
Screenshot:

Categories