How to make Leaflet Search actually search - javascript

Implementing the Leaflet Search example just produces a search box. Nothing happens when you open it and start typing. The leaflet search code isn't being executed. It just shows the red Location not found. The graph shows area's of interest and I need to do something with the area's that match search criteria, to identify them to the user.
var searchLayer = L.layerGroup().addTo(map);
//... adding data in searchLayer ...
map.addControl( new L.Control.Search({layer: searchLayer}) );
//searchLayer is a L.LayerGroup contains searched markers
There is code in the control to search to the data. It takes into account a geoJson data structure.
What am I missing in order to activate the search code?

Although not explicitly explained in Leaflet Control Search README, the plugin will use the data in marker.options.title or in feature.properties.title by default.
You can specify a different key than title using the propertyName option when instantiating the Search Control:
var map = L.map('map').setView([41.8990, 12.4977], 14);
var poiLayers = L.geoJSON(restaurant, {
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.amenity + '<br><b>' + feature.properties.name + '</b>');
}
});
L.control.search({
layer: poiLayers,
initial: false,
propertyName: 'name' // Specify which property is searched into.
})
.addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet-src.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet-search#2.3.7/dist/leaflet-search.src.css" />
<script src="https://unpkg.com/leaflet-search#2.3.7/dist/leaflet-search.src.js"></script>
<script src="http://labs.easyblog.it/maps/leaflet-search/examples/data/restaurant.geojson.js"></script>
<div id="map" style="height: 200px"></div>

Related

How to layer point feature over a polygon feature

How can I get a point feature over a polygon feature? I am layering polygon on top of the point feature or a marker feature however I also have a tooltip (popup) that fires when hovering over the features but only the polygon popup is getting displayed even when I am hovering over the point/marker feature. I am assured the point/marker is over/on top of the polygon because I assigned a 1.0 opacity and point/marker is still visible.
So when a point is on top of a polygon how can I get the popup on the point/marker feature to fire? Or is this a potential defect?
I swapped out the hover event for a 'click' event on the point/marker feature and the popup works as expected but this is not the desired behavior.
TIA!
Rick...
I've done a bunch of experimenting and its the order in which the events are added that make all the difference, not the order of the layers in this case. Unless you add the events to the map, rather than the individual layers, then the rendering order is used.
I've put together a little test app to test all the different scenarios:
var map, datasource, output, polygonLayer, pointLayer, isSwapped = false;
function GetMap() {
output = document.getElementById('output');
//Initialize a map instance.
map = new atlas.Map('myMap', {
center: [-122.1255, 47.6305],
zoom: 17,
view: 'Auto',
//Add your Azure Maps subscription key to the map SDK. Get an Azure Maps key at https://azure.com/maps
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: subscriptionKey
}
});
//Wait until the map resources are ready.
map.events.add('ready', function() {
//Create a data source and add it to the map.
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
//Add polygon to data source.
datasource.add(new atlas.data.Polygon(
[
[
[-122.126, 47.63096],
[-122.12602, 47.62997],
[-122.12537, 47.62994],
[-122.12534, 47.63094],
[-122.12600, 47.63096]
]
]
));
//Add point data
datasource.add(new atlas.data.Point([-122.1255, 47.6305]));
polygonLayer = new atlas.layer.PolygonLayer(datasource, null, {
fillColor: 'red'
});
pointLayer = new atlas.layer.SymbolLayer(datasource, null, {
filter: ['==', ['geometry-type'], 'Point']
});
map.layers.add([polygonLayer, pointLayer]);
map.events.add('mousemove', layerHovered);
});
}
function layerHovered(e) {
var msg = [];
if (e.shapes && e.shapes.length > 0) {
msg.push(e.shapes.length, ' shapes hovered.<ul>');
e.shapes.forEach(s => {
if (s instanceof atlas.Shape) {
msg.push('<li>Shape: ', s.getType(), '</li>');
} else {
msg.push('<li>Feature: ', s.geometry.type, ' (', s.source, ' -> ', s.sourceLayer, ')</li>');
}
});
msg.push('</ul>');
}
output.innerHTML = msg.join('');
}
function swapLayerOrder() {
map.layers.remove([pointLayer, polygonLayer]);
if (isSwapped) {
map.layers.add([polygonLayer, pointLayer]);
} else {
map.layers.add([pointLayer, polygonLayer]);
}
isSwapped = !isSwapped;
}
function changeEvents(elm) {
map.events.remove('mousemove', layerHovered);
map.events.remove('mousemove', pointLayer, layerHovered);
map.events.remove('mousemove', polygonLayer, layerHovered);
switch (elm.value) {
case 'map':
map.events.add('mousemove', layerHovered);
break;
case 'ps':
map.events.add('mousemove', [polygonLayer, pointLayer], layerHovered);
break;
case 'sp':
map.events.add('mousemove', [pointLayer, polygonLayer], layerHovered);
break;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
</head>
<body onload="GetMap()">
<div id="myMap" style="position:relative;width:100%;height:600px;"></div>
<div style="position:absolute;top: 10px;left:10px;background-color:white;padding:10px;">
<input type="button" onclick="swapLayerOrder()" value="Swap layer order"/>
<br/><br/>
Attach event to:<br/>
<input type="radio" name="gender" value="map" checked="checked" onclick="changeEvents(this)"/> map<br/>
<input type="radio" name="gender" value="ps" onclick="changeEvents(this)"/> polygon layer then symbol layer<br/>
<input type="radio" name="gender" value="sp" onclick="changeEvents(this)"/> symbol layer then polygon layer<br/>
<br/>
<div id="output"></div>
</div>
<script>var subscriptionKey = atob('dFRrMUpWRWFlTnZEa3h4bnhIbTljWWFDdnFsT3ExdS1mWFR2eVhuMlhrQQ==')</script>
</body>
</html>

importe markers from database usin HERE MAPS API

Iam trying to use HERE MAPS API, and i want to get markers from mySQL database, i am using the api like showing in here forume but markers doesnt shown im the map, i ma using this code :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1542186754" />
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-clustering.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 400px; background: grey" />
<script type="text/javascript" charset="UTF-8" >
/**
* Display clustered markers on a map
*
* Note that the maps clustering module http://js.api.here.com/v3/3.0/mapsjs-clustering.js
* must be loaded to use the Clustering
* #param {H.Map} map A HERE Map instance within the application
* #param {Array.<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
var platform = new H.service.Platform({
app_id: 'devportal-demo-20180625',
app_code: '9v2BkviRwi9Ot26kp2IysQ',
useHTTPS: true
});
var pixelRatio = window.devicePixelRatio || 1;
var defaultLayers = platform.createDefaultLayers({
tileSize: pixelRatio === 1 ? 256 : 512,
ppi: pixelRatio === 1 ? undefined : 320
});
// Step 2: initialize a map
var map = new H.Map(document.getElementById('map'), defaultLayers.normal.map, {
center: new H.geo.Point(30.789, 33.790),
zoom: 2,
pixelRatio: pixelRatio
});
// 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: request a data about airports's coordinates
var url= 'https://jsondataexemple.com/hereapi/jsondata.json';
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
success: function (data) {
startClustering(map, data);
}
});
</script>
</body>
</html>
the Json file is generated from my database by a php script :
[{"id":2812,"latitude":"33.5706476858027","longitude":"-7.600212045766735"},{"id":2811,"latitude":"33.56960668831451","longitude":"-7.6025319565980904"}]
thanks for helping me
In your json, latitude, longitude seems to be String. they should Float.
you may consider using ParseFloat in JS or change your php script.
after testing chrome debuger i found that the probleme is from my local host, but the code work properly in my online host !.
sorry

Leaflet map not displaying external GeoJSON data

Leaflet Map not Visible ....
What I am trying to do is creating a map and add external GeoJSON file I already created through QGIS app using SPH file from http://naturalearthdata.com
somehow my map is not visible there i also tried to use mapbox and google API key with leaflet library and sill having same issue
anyone knows the solution ??
I couldn't add my GeoJSON file in here because it's a huge file
Here is my HTML file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="biewport" content="width=device-width, initial-scale=1" />
<title>GeoJSON</title>
<!-- leflet links -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.3.3/dist/leaflet.js"></script>
</head>
<body>
<div id="map"></div>
<!-- <script src="CA_Bulletin_118_Groundwater_Basins.geojson"></script> -->
<script src="test.geojson"></script>
<!-- script file -->
<script src="js/script.js"></script>
</body>
</html>
My script.js file:
//creating a new map
var map = new L.Map('map').setView([51.505, -0.09], 13);
//create a new Geojason layer and set it up to basins var ....
// var test;
var test = L.tileLayer('basins');
var basinslayer = L.geoJson(basins).addTo(map);
And here is my CSS file:
/*General CSS */
html, body, #map {
height: 100%;
width: 100%;
font-family: sans-serif;
}
#map {
width: 50%;
height: 50%;
}
I'm also importing a geojson file to generate the points on my map. I used the $.getJSON from jquery to import the geojson file, load the data, and create the points.
If you want to try this method, you have to add jQuery in the head of your html, like this (also found here for the latest cdn):
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
My $.getJSON looks like this:
var getjson = $.getJSON("map-v2.geojson",function(data){
var bev = L.geoJson(data,{
pointToLayer: function(feature,latlng){
var marker = L.marker(latlng);
marker.bindPopup('<p align=center>' + '<strong>Title: </strong>' + feature.properties.Title + '<strong>Date: </strong>' + feature.properties.Date + '<br/>' + '<strong>Creator: </strong>' + feature.properties.Creator);
return marker;
}
});
bev.addTo(map);
});
First, I set a variable that calls $.getJSON, which takes a few arguments, the first one is the name of the geoJSON file in quotes, and the second is function(data) which acts to say we are going to use the data found in this file. The second line I assign my variable bev to invoke the L.geoJson function, passing the argument data (which will use the data from the geoJSON file). Then I point to a new layer using pointToLayer and assigning it the value of the function(feature,latlng). feature allows me to name certain properties from my geoJSON file to display in the popups, latlng extracts the coordinates from the geoJSON file to generate the locations for the markers(latlng is mandatory). I then assign another variable called marker, and here's where you generate your markers on your map, simply by using L.marker(latlng). After that, the marker.bindPopup binds all the content I want to display on popups from the properties data I have in each of my points in the geoJson file. Here's an example of my geoJSON:
{
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.714055,
38.440429
]
},
"properties": {
"Title": "Santa Rosa. Sonoma County. California. 1885.",
"Date": "1885",
"Creator": "W.W. Elliot & Co., lithographer."
}
},
I then return the marker, add the variable bev to the map, and there they are!
*I'm not an expert on JavaScript or Leaflet, so if my wording is off, I will gladly make edits to make it clearer.

Generate PDF from HTML with Map (exactly a screenshot)

Hi I have this html with some content and a map, using Leaflet api for map rendering (jsfiddle) This whole content is part of a modal panel which open on a button click after user input some data. I want to export all content into a pdf with some client side solution.
I have tried jspdf like but it does not works. tried combination of canvastohtml and jspdf like but could not able to make it work either. Point to mentione here is my content contains map which export jspdf doesn't support
Anyone knows a solution, please share. I have included the code below
PS: Using phamtomjs screenshot utilities is not an option
<script src="https://npmcdn.com/leaflet#1.0.0-rc.3/dist/leaflet.js"></script>
<link href="https://npmcdn.com/leaflet#1.0.0-rc.3/dist/leaflet.css" rel="stylesheet" />
<body>
<script>
function createMap(mapPlaceHolderId) {
var OSM_MAP_TILE_SERVER_URL = 'http://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png';
var DEFAULT_MAP_CENTER = L.latLng(25.296854389343867, 51.48811340332031);
var DEFAULT_MAP_ZOOM = 12;
var MAP_ZOOM_MAX = 19;
var MAP_ZOOM_SEARCH = 17;
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib = 'Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {
minZoom: 8,
maxZoom: 12,
attribution: osmAttrib
});
var map = L.map(mapPlaceHolderId).setView([51.505, -0.09], 13);
map.addLayer(osm);
return map;
}
</script>
<div id="vrSubReportContainer">
<div class="mapPopupTableContainer">
<div class="mapPopupTableData"><b>Plate Number:</b> 009-001GL-297286, <b>Driver Name:</b> Unknown driver
<br><b>Latitude,Longitude</b>: 25.215238,51.605439</div>
</div>
<div id="mapContainer" class="map-container">
<div class="map" id="fd_map_canvas"></div>
</div>
</div>
<script>
(function() {
createMap('fd_map_canvas');
})();
</script>
</body>

ArcGIS API for JavaScript, NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

I'm following this guide:
https://developers.arcgis.com/javascript/jshelp/intro_agstemplate_amd.html
I am using the Web Map ID that they do In the tutorial: 1a40fa5cc1ab4569b79f45444d728067
However, when I run my code:
var map;
require([
"esri/map",
"esri/arcgis/utils",
"dojo/domReady!"
], function(Map, arcgisUtils) {
arcgisUtils.arcgisUrl = "file:///C:/Users/Bryan/Desktop/gis.html";
arcgisUtils.createMap("1a40fa5cc1ab4569b79f45444d728067 ", "mapDiv").then(function(response) {
map = response.map;
});
});
I get the following error:
NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
In the tutorial they say the following:
To access a web map from a portal outside of ArcGIS Online, reference
the arcgisUrl property and set the path to your portal URL before
calling the createMap() method:
arcgisUtils.arcgisUrl = "http://pathto/portal/sharing/content/items";
But what is a portal URL? What is my portal URL?
We will go step by step to resolve above issue:
First of all you should know your the webmap ID 1a40fa5cc1ab4569b79f45444d728067 you are using its public or private. I mean it accessible by everyone or by the created person who created it.
As you can see I can access this Id globally so it mean its not private so you don't need to add portal url
(Below are the two way you can access your webmap just replace web map id at the end of below urls).
Item details of above Webmap ID: click here to see the details of webmap id.
Webmap ID in map viewer: click here to see webmap id in map viewer.
Portal url is needed only when if the webmap id is not shared to everyone.
Portal URL: Whenever you sign up to arcgis.com after that it creates a unique portal url (The server name where Portal for ArcGIS is installed) for each user. This unique url we need to configure only when if webmap/item is not shared to everyone. In this case it take automatically "arcgis online default portal url".
Now go to this online sample and replace your webmap id there. It will work properly.
Running Code:
require([
"dojo/parser",
"dojo/ready",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dojo/dom",
"esri/map",
"esri/urlUtils",
"esri/arcgis/utils",
"esri/dijit/Legend",
"esri/dijit/Scalebar",
"dojo/domReady!"
], function(
parser,
ready,
BorderContainer,
ContentPane,
dom,
Map,
urlUtils,
arcgisUtils,
Legend,
Scalebar
) {
ready(function(){
parser.parse();
//if accessing webmap from a portal outside of ArcGIS Online, uncomment and replace path with portal URL
//arcgisUtils.arcgisUrl = "https://pathto/portal/sharing/content/items";
arcgisUtils.createMap("1a40fa5cc1ab4569b79f45444d728067 ","map").then(function(response){
//update the app
dom.byId("title").innerHTML = response.itemInfo.item.title;
dom.byId("subtitle").innerHTML = response.itemInfo.item.snippet;
var map = response.map;
//add the scalebar
var scalebar = new Scalebar({
map: map,
scalebarUnit: "english"
});
//add the legend. Note that we use the utility method getLegendLayers to get
//the layers to display in the legend from the createMap response.
var legendLayers = arcgisUtils.getLegendLayers(response);
var legendDijit = new Legend({
map: map,
layerInfos: legendLayers
},"legend");
legendDijit.startup();
});
});
});
<link rel="stylesheet" href="https://js.arcgis.com/3.16/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.16/esri/css/esri.css">
<link rel="stylesheet" href="http://developers.arcgis.com/javascript/sandbox/css/styles.css">
<script src="https://js.arcgis.com/3.16/"></script>
<body class="claro">
<div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline'" style="width:100%; height:100%;">
<div id="header" class="shadow roundedCorners" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top'">
<div id="title"></div>
<div id="subtitle"></div>
</div>
<div id="map" class="roundedCorners shadow" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'"></div>
<div id="rightPane" class="roundedCorners shadow" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'right'" >
<div id="legend"></div>
</div>
</div>
</body>

Categories

Resources