I am using Mapbox.js with browserify. I want to create a module that creates a map if it does not already exist, but updates it if it does.
I have got almost all the way there, but I'm having problems with updating the custom legend. I only seem to be able to append to it, and can't clear it.
This is my code:
var analyseMap = {
setUpMap: function(options) {
var _this = this;
L.mapbox.accessToken = 'mytoken';
if (typeof this.map === 'undefined') {
this.map = L.mapbox.map('map', 'mapbox.streets').setView([53.1, -2.2], 6);
this.layerGroup = L.layerGroup().addTo(this.map);
} else {
this.layerGroup.clearLayers();
}
var geojson_url = "/api/1.0/myurlbasedonoptions";
$.getJSON(geojson_url, function(boundaries) {
var orgLayer = L.geoJson(boundariesWithData, { style: getStyle });
_this.layerGroup.addLayer(orgLayer);
_this.map.fitBounds(orgLayer.getBounds());
var popup = new L.Popup({ autoPan: false });
var legendHtml = _this.getLegendHTML(options);
_this.map.legendControl.removeLegend();
_this.map.legendControl.addLegend(legendHtml);
Then I call it from another module like this:
// on initialise and update
map.setUpMap(someOptions);
This works just great the first time I call it. However, on update, the map updates and the layers update nicely, but I end up with two legends.
How can I clear the existing legend before adding the new one?
The documentation suggests that I need to know the value of the legend HTML in order to remove it, which seems strange.
OK, I fixed it by doing this:
if (typeof _this.legendHtml !== 'undefined') {
_this.map.legendControl.removeLegend(_this.legendHtml);
}
_this.legendHtml = _this.getLegendHTML(_this.quintiles, options);
_this.map.legendControl.addLegend(_this.legendHtml);
Would still be interested to see if anyone has a more elegant solution though!
Related
I'm currently trying to create a map application, so far the map loads and the custom information and icons work flawlessly. I'd, however, like to show the user how far away (distance) to the marker on the map.
This code is working, but I'd like the "from" variable to be the users current position instead of a predetermined position.
var onePlace = L.marker([63, 20], {icon: thisIcon}).bindPopup('My text'),
theOtherPlace = L.marker([65, 20], {icon: thatIcon}).bindPopup('My text');
var to = onePlace.getLatLng();
var from = theOtherPlace.getLatLng();
var distance = from.distanceTo(to);
To set the users position on the map I use the code from their quickstart guide whick looks something like this
primaryMap.locate({
});
primaryMap.on('locationfound', positionFound);
primaryMap.on('locationerror', positionNotFound);
function positionFound(e) {
var myPosition = L.marker(e.latlng, {
}).addTo(primaryMap);
}
function positionNotFound(e) {
alert(e.message);
}
But how to get the position that I set here in a later stage is what I'm struggling with.
Basically, what I want is this
var myPos = [??].getLatLng();
var to = onePlace.getLatLng();
var distance = myPos.distanceTo(to);
Sorry for the strange formatting on some of the code, first time posting.
Anyway, if someone could help me out here I'd be incredibly thankful. Been stuck on this one problem for forever and can't seem to find anything helpful in the documentation (probably just don't quite understand it as I'm rather new to this).
Thanks in advance!
UPDATE:
jsfiddle: https://jsfiddle.net/xcyniic/98sy6zxb/27/
Maybe this can help shed some light on what I'm doing / have done wrong.
You get the latlng from the locationfound event.
primaryMap.on('locationfound', positionFound);
function positionFound(e) {
var myPos = e.latlng;
var to = onePlace.getLatLng();
var distance = myPos.distanceTo(to);
}
Update
To get the pos value outside you have to create the variable outside and test if it is not null;
var myPos = null;
primaryMap.on('locationfound', positionFound);
function positionFound(e) {
myPos = e.latlng;
calcDistances();
}
function calcDistances(){
if(myPos){
var to = onePlace.getLatLng();
var distance = myPos.distanceTo(to); +
var to2 = twoPlace.getLatLng();
var distance = myPos.distanceTo(to2);
//...
}
}
I think that you are thinking wrong. The locationfound event is not called immediately, it is a async service. So you have to calc the distance after the event is called and the user position is found.
I'm migrating from Google Maps API to Apple MapKit JS for the simple reason I have a developer account with them and they offer more free hits.
Anyway, actual examples of MapKit JS are a bit thin (or at least Google isn't finding them - draw what conspiracy theories you will), so although I've got the basics going of displaying an embeded map, I can't seem to do the next step which is route between two points (Apple's documentation also seems impenetrable as they don't show examples).
Here's my script for a basic map:
<script>
mapkit.init({
authorizationCallback: function(done) {
done('[MY-TOKEN]');
}
});
var MarkerAnnotation = mapkit.MarkerAnnotation
var myMarker = new mapkit.Coordinate(55.9496320, -3.1866360)
var myRegion = new mapkit.CoordinateRegion(
new mapkit.Coordinate(55.9496320, -3.1866360),
new mapkit.CoordinateSpan(0.003, 0.003)
);
var map = new mapkit.Map("map");
var myAnnotation = new MarkerAnnotation(myMarker, { color: "#9b6bcc", title: "theSpace On The Mile"});
map.showItems([myAnnotation]);
map.region = myRegion;
</script>
Now I want to:
• Show a walking route between two points
• Include waypoints on the route
Could someone show the code that would achieve this? Once I can see an example I know I'll get it ;-)
Ok, so I've found a solution to this so sharing it here for the benefit of others.
Let's start by saying Apple's MapKit JS doesn't appear to have a waypoints option as offered by Google Maps API - so the way around that is to create a map that stores the markers in an array and then routes from one to the next. The code stores the location of the last waypoint in a variable, and doesn't bother to draw a route to the last waypoint if this is the first one in the array (obviously).
<script>
// Initiallise MapKit - you'll need your own long-lived token for this
mapkit.init({
authorizationCallback: function(done) {
done('[MY-TOKEN]');
}
});
// Function to draw the route once MapKit has returned a response
function directionHandler(error, data) {
data["routes"].forEach(function(route, routeIdx) {
if (routeIdx !== 0) { return; }
overlays = [];
route['path'].forEach(function(path) {
// This styles the line drawn on the map
let overlayStyle = new mapkit.Style({
lineWidth: 3,
strokeColor: "#9b6bcc"
});
let overlay = new mapkit.PolylineOverlay(path, {
style: overlayStyle
});
overlays.push(overlay);
});
map.addOverlays(overlays);
});
}
// This asks MapKit for directions and when it gets a response sends it to directionHandler
function computeDirections(origin,destination) {
let directionsOptions = {
origin: origin,
destination: destination,
transportType: mapkit.Directions.Transport.Walking
};
directions.route(directionsOptions, directionHandler);
}
// This sets the initial region, but is overridden when all points have been potted to automatically set the bounds
var myRegion = new mapkit.CoordinateRegion(
new mapkit.Coordinate(55.9496320, -3.1866360),
new mapkit.CoordinateSpan(0.05, 0.05)
);
var map = new mapkit.Map("map");
map.region = myRegion;
var myAnnotations = [];
// lastWaypoint variable is 'unset' initially so the map doesn't try and find a route to the lastWaypoint for the first point of the route
var lastWaypoint = "unset";
var directions = new mapkit.Directions();
// Array of co-ordinates and label for marker
waypoints = [
{name:'Sofi’s Bar',lat:55.9746308,lon:-3.1722282},
{name:'TThe Roseleaf Cafe',lat:55.975992,lon:-3.173474},
{name:'Hemingway’s',lat:55.9763631,lon:-3.1706564},
{name:'Teuchter’s Landing',lat:55.9774693,lon:-3.1713826},
{name:'The King’s Wark',lat:55.9761425,lon:-3.1695419},
{name:'Malt and Hops',lat:55.975885,lon:-3.1698957},
{name:'The Carrier’s Quarters',lat:55.9760813,lon:-3.1685323},
{name:'Noble’s',lat:55.974905,lon:-3.16714},
{name:'The Fly Half',lat:55.9747906,lon:-3.1674496},
{name:'Port O’ Leith',lat:55.974596,lon:-3.167525}
];
// Loop through the array and create marker for each
waypoints.forEach(function(data) {
var myAnnotation = new mapkit.MarkerAnnotation(new mapkit.Coordinate(data['lat'],data['lon']), {
color: "#9b6bcc",
title: data['name']
});
myAnnotations.push(myAnnotation);
// As long as this isn't the first point on the route, draw a route back to the last point
if(lastWaypoint!="unset") {
computeDirections(lastWaypoint,new mapkit.Coordinate(data['lat'],data['lon']));
}
lastWaypoint = new mapkit.Coordinate(data['lat'],data['lon']);
});
map.showItems(myAnnotations);
</script>
This map is for a pub crawl around Leith, so the trasportType is 'Walking', but change that to 'Automobile' if you so wish.
With credit to Vasile whose MapKit JS Demo (https://github.com/vasile/mapkit-js-demo) helped me understand a lot more about the options.
I am not really good at js and trying to use Bing map in our website but it shows the map few times and doesnt show the map most of the time. Below is the code snippet of loading map function, can someone please let me know whats wrong in this function, I am using this from other application:
function loadMap(storeData) {
var coordinates = {};
var map;
var stores = storeData.stores;
if( (typeof stores !== 'undefined') && (typeof stores[0].coordinates !== 'undefined') ) {
coordinates.lat = stores[0].coordinates.lat;
coordinates.lng = stores[0].coordinates.lng;
}else {
coordinates.lat = 33.74831008911133;
coordinates.lng = -84.39111328125;
}
map = new Microsoft.Maps.Map($('#bingMap')[0], {
credentials: 'mykey',
liteMode: true,
enableClickableLogo: false,
center: new Microsoft.Maps.Location(coordinates.lat, coordinates.lng)
});
self.center = new Microsoft.Maps.Location(coordinates.lat, coordinates.lng);
map.setView({zoom: 13});
return map;
}
I have tried below few steps I got from other stackoverflow queries but it didnt help me:-(
setTimeout(this.loadMap(storeData), 2000); Microsoft.Maps.Events.addHandler(map,'resize')
The problem is in your setTimeout call:
You see, setTimeout receives 2 parameters:
A function to execute
Timeout in ms
in your case, you used setTimeout(this.loadMap(storeData), 2000); which doesn't pass the function to the setTimeout but the result of the execution. In addition, this code will also execute this.loadMap immediately and not in 2 seconds.
To solve this, you can just use:
setTimeout(function() { this.loadMap(storeData)}, 2000);
or: (#Sysix's solution)
setTimeout(this.loadMap.bind(this), 2000, storeData);
I'm developing an Android application containing a Webview. The HTML corresponding to the webview contains mainly JavaScript code ; it retrieves a map of a building from a Geoserver. I use Leaflet to display the different layers. Each base layer is a floor.
I'm adding 2 overlays to the base layers from Android ; one is a heatmap, the other is a set of markers representing the locations of some sensors. Thanks to a JavaScript interface in Android, the JavaScript code can get datasets created from Android.
It works when I display only ONE of the overlays. As soon as I want to display both overlays, or after I displayed an overlay, hid it, and display the other, the application crashes. I have different errors according to the overlay added first.
Something really strange : it only happens with my tablet (which is very cheap), not with the AVD.
Here is my JavaScript code :
<script type="text/javascript" charset="utf-8">
var map, baseLayers, heatmapLayer, sensorsLayer;
var ground_floor = new L.tileLayer.wms('http://192.168.1.16/geoserver/wms',
{
layers: 'ground_floor',
format: 'image/png'
});
var first_floor = new L.tileLayer.wms('http://192.168.1.16/geoserver/wms',
{
layers: 'first_floor',
format: 'image/png'
});
var second_floor = new L.tileLayer.wms('http://192.168.1.16/geoserver/wms',
{
layers: 'second_floor',
format: 'image/png'
});
var current_floor = ground_floor;
baseLayers = {
"Ground floor": ground_floor,
"First floor": first_floor,
"Second floor": second_floor
};
map = new L.Map('map', {
center: new L.LatLng(-45, 170),
zoom: 30,
layers: [ground_floor],
crs: L.CRS.EPSG900913
}).setView([-45.8668664, 170.5185323], 31);
var control = L.control.layers(baseLayers).addTo(map);
map.on('baselayerchange', onBaseLayerChanged);
// Called when the base layer (meaning the floor) is changed
function onBaseLayerChanged(event) {
// Update the current floor
if (event.layer == ground_floor)
current_floor = ground_floor;
else if (event.layer == first_floor)
current_floor = first_floor;
else if (event.layer == second_floor)
current_floor = second_floor;
else
Android.debug("Wrong base layer");
Android.debug("yo1");
// Update the heatmap and sensors' location
// if they are displayed
if (map.hasLayer(heatmapLayer)) {
removeHeatmap();
addHeatmap();
}
Android.debug("yo2");
if (map.hasLayer(sensorsLayer)) {
Android.debug("yo3");
removeSensors();
addSensors();
Android.debug("yo4");
}
}
function addHeatmap() {
heatmapLayer = L.TileLayer.heatMap({
// radius could be absolute or relative
// absolute: radius in meters, relative: radius in pixels
radius: { value: 5, absolute: true },
opacity: 0.8,
gradient: {
0.45: "rgb(0,0,255)",
0.55: "rgb(0,255,255)",
0.65: "rgb(0,255,0)",
0.95: "yellow",
1.0: "rgb(255,0,0)"
}
});
var dataSet;
if (current_floor == ground_floor)
dataSet = JSON.parse(Android.getDataSetGroundFloor());
else if (current_floor == first_floor)
dataSet = JSON.parse(Android.getDataSetFirstFloor());
else if (current_floor == second_floor)
dataSet = JSON.parse(Android.getDataSetSecondFloor());
else
Android.debug("Error getDataSet : wrong floor");
heatmapLayer.setData(dataSet.data);
control.addOverlay(heatmapLayer, "Heatmap");
heatmapLayer.addTo(map);
}
function removeHeatmap() {
control.removeLayer(heatmapLayer);
map.removeLayer(heatmapLayer);
}
function addSensors() {
var sLat, sLon;
var markers = new Array();
if (current_floor == ground_floor) {
sLat = JSON.parse(Android.getLatitudesGroundFloor());
sLon = JSON.parse(Android.getLongitudesGroundFloor());
}
else if (current_floor == first_floor) {
sLat = JSON.parse(Android.getLatitudesFirstFloor());
sLon = JSON.parse(Android.getLongitudesFirstFloor());
}
else if (current_floor == second_floor) {
sLat = JSON.parse(Android.getLatitudesSecondFloor());
sLon = JSON.parse(Android.getLongitudesSecondFloor());
}
else
Android.debug("Error getCoordinates : wrong floor");
for (i=0; i<sLat.length && i<sLon.length; i++) {
var marker = L.marker([sLat[i],sLon[i]]);
markers.push(marker);
}
sensorsLayer = L.layerGroup(markers);
control.addOverlay(sensorsLayer, "Sensors");
sensorsLayer.addTo(map);
}
function removeSensors() {
control.removeLayer(sensorsLayer);
map.removeLayer(sensorsLayer);
}
</script>
If I add the heatmap first, and then the sensors I have a NullPointerException on "sensorsLatFloor" of the following code :
public JSONArray getLatitudesGroundFloor() {
if (!isSensorsQueryDone())
new SelectSensorsLocationATask(SensorsFragment.this).execute();
// Wait for the end of the query
while (!querySuccessful) {}
JSONArray latJSON = null;
latJSON = new JSONArray(sensorsLatGroundFloor);
return latJSON;
}
This is for the ground floor but it does the same for every floor. "sensorsLatGroundFloor" is an ArrayList filled by the AsyncTask SelectSensorsLocationATask after a query in the local database. The code works, since it works when I only want to display sensors.
When I display the sensors first, and then the heatmap, the app crashes and I have the following error in the LogCat :
JNI ERROR (app bug): accessed staled weak global reference 0xffffffff (index 65535 in a table of size 8)
VM aborting
Fatal signal 11 (SIGSEV) at 0xdeadd00d
This is very odd, because I don't manipulate JNI code at all...
Besides, I have another error, which must be very stupid but I don't figure out why it doesn't work. Have a look at this part of my JavaScript code :
// Called when the base layer (meaning the floor) is changed
function onBaseLayerChanged(event) {
// Update the current floor
if (event.layer == ground_floor)
current_floor = ground_floor;
else if (event.layer == first_floor)
current_floor = first_floor;
else if (event.layer == second_floor)
current_floor = second_floor;
else
Android.debug("Wrong base layer");
Android.debug("yo1");
// Update the heatmap and sensors' location
// if they are displayed
if (map.hasLayer(heatmapLayer)) {
removeHeatmap();
addHeatmap();
}
Android.debug("yo2");
if (map.hasLayer(sensorsLayer)) {
Android.debug("yo3");
removeSensors();
addSensors();
Android.debug("yo4");
}
}
This function is supposed to update the overlay(s) displayed when I switch the base layer (meaning the floor). It works with the heatmap, but not with the sensors... If the heatmap is not on the map, the function is finished, it doesn't even look at my second if. You can see my "Android.debug", it displays in the LogCat the message I put as parameter. Here, the LogCat only displays "yo1".
EDIT : I figured something out about this last error. The problem seems to be the Leaflet function "hasLayer". If the map has the layer indicated, it returns true. So in my mind, if it doesn't, it's supposed to return false... It makes sense. But instead of it, it makes the code bug, so the code after the function is ignored. Either I'm making a mistake that I don't see when I call it, or Leaflet made a useless function... So I must have done a silly mistake but I don't find it !
I hope I've been clear enough to let you understand my problems... Let me know if you need more Android code, although I don't think it would be helpful.
Thanking you in advance.
* PROBLEM FIXED *
The errors were caused by a problem of task synchronisation in the Android code. You can see that I wait for the end of the query with the variable "querySuccessful". Actually I was manipulating this variable from the AsyncTask only : I set it to false at the beginning and true at the end. Now I set it to true before I start the AsyncTask, and the application works, I have no more errors.
I still have some problems with the Leaflet function hasLayer ; it works when I switch the base layer once, sometimes twice, but then it stops working. But apparently it might be an error from Leaflet, which will be fixed in the next release.
A similar issue to that described in OpenLayers: destroyed features reappear after zooming in or out
Call destroyFeatures() or removeAllFeatures() (or both, in either order) on a vector layer. The features disappear from view. But then zoom in or out, and they reappear. For me, this only happens if a clustering strategy is being used. It almost seems as if the cluster feature is destroyed but the underlying features represented by that cluster are not, so, when you zoom in or out the clustering is recalculated from those underlying features and re-drawn.
Googling reveals a number of conversations among the developers of OpenLayers a few years ago concerning issues with destroyFeatures(). It's surprising that, even now, the issues don't seem to have been fully resolved.
I can get around the problem by destroying the whole layer (using destroy()) and then recreating it when needed. That's OK in my case, but I can imagine cases where such a blunderbuss approach might not be desirable.
In response to the request for a code sample, here is an abbreviated version of the code in the version that is working (ie, using destroy()). In the non-working version, I called destroyFeatures() instead (and did not set the layer to null). As stated above, this would erase the features initially, but if I then zoomed in or out using this.map.zoomIn(), the features would reappear.
Note 1: the functions are called from Objective-C via the JavaScript bridge.
Note 2: the JavaScript was generated using CoffeeScript.
(function() {
var addSightingsLayer, displayFeaturesForSightingsWithGeoJSONData, geoJSONFormat, load, map, projectionSphericalMercator, projectionWGS84, removeSightingsLayer, sightingsLayer;
addSightingsLayer = function() {
var context, layerStyle, layerStyleSelected, style, styleMap, styleSelected, yerClusteringStrategy;
if (!(this.sightingsLayer === null)) return;
yerClusteringStrategy = new OpenLayers.Strategy.Cluster({
distance: 10,
threshold: 2
});
this.sightingsLayer = new OpenLayers.Layer.Vector('Sightings', {
strategies: [yerClusteringStrategy]
});
this.map.addLayer(this.sightingsLayer);
style = {
// Here I define a style
};
context = {
// Here I define a context, with several functions depending on whether there is a cluster or not, eg:
dependentLabel: function(feature) {
if (feature.cluster) {
return feature.attributes.count;
} else {
return feature.attributes.name;
}
}, ....
};
layerStyle = new OpenLayers.Style(style, {
context: context
});
styleSelected = {
//...
};
layerStyleSelected = new OpenLayers.Style(styleSelected, {
context: context
});
styleMap = new OpenLayers.StyleMap({
'default': layerStyle,
'select': layerStyleSelected
});
this.sightingsLayer.styleMap = styleMap;
};
removeSightingsLayer = function() {
if (this.sightingsLayer === null) return;
this.sightingsLayer.destroy();
return this.sightingsLayer = null;
};
displayFeaturesForSightingsWithGeoJSONData = function(geoJSONData) {
if (this.sightingsLayer === null) JFOLMap.addSightingsLayer();
return this.sightingsLayer.addFeatures(this.geoJSONFormat.read(geoJSONData));
};
load = function() {
var lat, lon, osmLayer, zoom;
lat = ...;
lon = ...;
zoom = ...;
this.map = new OpenLayers.Map('mapDiv', {
controls: ...,
eventListeners: ...
});
osmLayer = new OpenLayers.Layer.OSM();
this.map.addLayer(osmLayer);
return this.map.setCenter(new OpenLayers.LonLat(lon, lat).transformWGS84ToSphericalMercator(), zoom);
};
OpenLayers.LonLat.prototype.transformWGS84ToSphericalMercator = function() {
return this.transform(JFOLMap.projectionWGS84, JFOLMap.projectionSphericalMercator);
};
OpenLayers.LonLat.prototype.transformSphericalMercatorToWGS84 = function() {
return this.transform(JFOLMap.projectionSphericalMercator, JFOLMap.projectionWGS84);
};
map = null;
sightingsLayer = null;
sightingsPopoverControl = null;
projectionWGS84 = new OpenLayers.Projection('EPSG:4326');
projectionSphericalMercator = new OpenLayers.Projection('EPSG:900913');
geoJSONFormat = new OpenLayers.Format.GeoJSON({
'externalProjection': projectionWGS84,
'internalProjection': projectionSphericalMercator
});
this.JFOLMap = {
map: map,
sightingsLayer: sightingsLayer,
projectionSphericalMercator: projectionSphericalMercator,
projectionWGS84: projectionWGS84,
geoJSONFormat: geoJSONFormat,
load: load,
addSightingsLayer: addSightingsLayer,
removeSightingsLayer: removeSightingsLayer,
displayFeaturesForSightingsWithGeoJSONData: displayFeaturesForSightingsWithGeoJSONData,
};
}).call(this);
Try this, it worked for me
layer.removeAllFeatures();
layer.destroyFeatures();//optional
layer.addFeatures([]);