Displaying PostGIS Data with Leafletjs - javascript

I'm learning GIS with PostGIS and I wanted to try something funny so I downloaded shape files from OSM, imported in PostGres with PostGIS extension and now I want to represent data from PostGIS visually. I have Pulled data with Query
SELECT ST_AsGeoJSON(geom) FROM "dar-es-salaam_tanzania.land_coast;
I got bunch of GeoJSON and wanted to show them to user. Unfortunately it does not show it. I use Yii2 to write codes that pulls the data. Here is the controller code:
public function actionIndex()
{
$cmd = Yii::$app->db->createCommand('SELECT ST_AsGeoJSON(geom) FROM "dar-es-salaam_tanzania.land_coast";');
$gjsons = [];
foreach($cmd->queryAll() as $row)
{
$gjsons[] = json_decode($row['st_asgeojson']);
}
return $this->render('index', ['geojson'=>json_encode($gjsons)]);
}
and in view
<?php
/* #var $this yii\web\View */
$this->title = 'Map Application';
$this->registerJs("
var map = L.map('map').setView([6.8000, 39.2833], 13);
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'examples.map-20v6611k'
}).addTo(map);
var geojsonList = $geojson;
L.geoJson(geojsonList).addTo(map);
");
?>
<div id="map">
</div>
Is there something that am missing? I'm new to leaflet library and am following their tutorials on their site
UPDATE
Here is the HTML Output (stripped Geojson to fit SO) here is full source
Note that I set Height of the map and I can see a grey box with (+) and (-) signs on it but no map is shown.
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Map Application</title>
<link href="/tech/maps-app/web/assets/7edc4543/css/bootstrap.css" rel="stylesheet">
<link href="/tech/maps-app/web/css/site.css" rel="stylesheet">
<link href="/tech/maps-app/web/css/map.css" rel="stylesheet">
<link href="/tech/maps-app/web/leafletjs/leaflet.css" rel="stylesheet"></head>
<body>
<div class="wrap">
<div id="map">
</div>
</div>
</script><script src="/tech/maps-app/web/assets/c29e8e0a/jquery.js"></script>
<script src="/tech/maps-app/web/assets/f3e1524/yii.js"></script>
<script src="/tech/maps-app/web/leafletjs/leaflet.js"></script>
<script src="/tech/maps-app/web/assets/7edc4543/js/bootstrap.js"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
var map = L.map('map').setView([6.8000, 39.2833], 13);
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'examples.map-20v6611k'
}).addTo(map);
var geojsonList = [{"type":"MultiPolygon","coordinates":[[[[39.094989013528,-7.2022471828125],[38.638288027056,-7.2022471828125],[38.638288027056,-6.638130390625],[39.094989013528,-6.638130390625],[39.094989013528,-7.2022471828125]]]]}];
L.geoJson(geojsonList).addTo(map);
});
</script>
</body>
</html>

You didn't set height container. Set in your css file:
#map {
height: 400px;
}
And set zoom. Like that:
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {zoom: 10, ...

Related

How to make Leaflet Search actually search

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>

Leaflet map marker clusters not showing icons

I'm trying to make a map with leafletjs, but I can't get marker clusters to work properly. I'd like it to show the default icons for marker clustering, but instead it shows no marker cluster icons at all. Here's a demonstration:
var map = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(map);
var markers = L.markerClusterGroup();
markers.addLayer(L.marker([51.505, -0.09]));
markers.addLayer(L.marker([51.506, -0.09]));
map.addLayer(markers);
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.1.0/dist/leaflet.css" integrity="sha512-wcw6ts8Anuw10Mzh9Ytw4pylW8+NAD4ch3lqm9lzAsTxg0GFeJgoAtxuCLREZSC5lUXdVyo/7yfsqFjQ4S+aKw==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.1.0/dist/leaflet.js" integrity="sha512-mNqn2Wg7tSToJhvHcqfzLMU6J4mkOImSPTxVZAdo+lcPlk+GhZmYgACEe0x35K7YzW1zJ7XyJV/TT1MrdXvMcA==" crossorigin=""></script>
<script src="https://leaflet.github.io/Leaflet.markercluster/dist/leaflet.markercluster-src.js"></script>
<div id="mapid" style="height:380px;"></div>
This code is completely based on the examples on http://leafletjs.com/examples/quick-start/ and https://github.com/Leaflet/Leaflet.markercluster#usage so I'd imagine it would work given those examples, but it doesn't seem like this actually shows the icons behind the clusters.
I have found that a markerClusterGroup has a method called _defaultIconCreateFunction, but it doesn't seem to get called (or if it does get called, it doesn't do anything).
So what am I doing wrong here?
You also need MarkerCluster.css and MarkerCluster.Default.css
var map = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(map);
var markers = L.markerClusterGroup();
markers.addLayer(L.marker([51.505, -0.09]));
markers.addLayer(L.marker([51.506, -0.09]));
map.addLayer(markers);
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.1.0/dist/leaflet.css" integrity="sha512-wcw6ts8Anuw10Mzh9Ytw4pylW8+NAD4ch3lqm9lzAsTxg0GFeJgoAtxuCLREZSC5lUXdVyo/7yfsqFjQ4S+aKw==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.1.0/dist/leaflet.js" integrity="sha512-mNqn2Wg7tSToJhvHcqfzLMU6J4mkOImSPTxVZAdo+lcPlk+GhZmYgACEe0x35K7YzW1zJ7XyJV/TT1MrdXvMcA==" crossorigin=""></script>
<link rel="stylesheet" href="https://leaflet.github.io/Leaflet.markercluster/dist/MarkerCluster.css" />
<link rel="stylesheet" href="https://leaflet.github.io/Leaflet.markercluster/dist/MarkerCluster.Default.css" />
<script src="https://leaflet.github.io/Leaflet.markercluster/dist/leaflet.markercluster-src.js"></script>
<div id="mapid" style="height:380px;"></div>

loading google maps in windows phone 8.1 using webview

I have created a sample app to load google maps in windows phone 8.1. Using the webview approch I'm not able to launch google maps, please help me in fixing this.. Below is the code:
default.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Maps</title>
<!-- WinJS references -->
<!-- At runtime, ui-themed.css resolves to ui-themed.theme-light.css or ui-themed.theme-dark.css
based on the user’s theme setting. This is part of the MRT resource loading functionality. -->
<link href="/css/ui-themed.css" rel="stylesheet" />
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- Maps references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<h1>Google Maps API on Windows phone 8.1</h1>
<x-ms-webview id="Map" src="ms-appx-web:///map.html" style="width:500px;height:500px;"></x-ms-webview>
</body>
</html>
maps.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- map references -->
<link href="/map.css" rel="stylesheet" />
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"></script>
<script src="/map.js"></script>
</head>
<body>
<div id="mapdisplay" height="500px" width="500px"></div>
</body>
</html>
maps.js:
var map;
var dataResults;
function initialize() {
map = new google.maps.Map(document.getElementById('mapdisplay'), {
zoom: 3,
center: new google.maps.LatLng(40, -187.3),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
addMarkers();
}
eqfeed_callback = function (results) {
dataResults = results;
}
function addMarkers() {
for (var i = 0; i < dataResults.features.length; i++) {
var quake = dataResults.features[i];
var coors = quake.geometry.coordinates;
var latLong = new google.maps.LatLng(coors[1], coors[0]);
var marker = new google.maps.Marker({
position: latLong,
map: map
//icon: getCircle(earthquake.properties.mag)
});
}
}
function getCircle(magnitude) {
return {
path: google.maps.SymbolPath.CIRCLE,
fillColor: 'red',
fillOpacity: .2,
scale: Math.pow(2, magnitude) / Math.PI,
strokeColor: 'white',
strokeWeight: .5
};
}
What's the mistake I'm doing in the above code, please let me know..
"maps.html" does not work because of multiple synchronicity issues.
Load maps.js beforehttp://maps.googleapis.com/maps/api/js so initialise is defined,
Load http://maps.googleapis.com/maps/api/jsand after the HTML has been parsed so the mapdisplay element exists when initialise is called.
Call addMarkers from eqfeed_callback not initialise so dataResults has been set with valid object data.
Most of this could have been found out by opening the developers console and checking it for errors when viewing "maps.html" in a desktop browser. You may also like to research other questions on the topic and/or check the api documentation for working examples - and notice how the api documentation uses defer and async attributes on the script tag to make sure it doesn't execute until after the page has been parsed.

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>

How to apply leaflet marker cluster using layers

I´m trying to apply the Leaflet.MarkerCluster.LayerSupport. But I don´t know how to use it :( I´ve already read the documentation about but and I tried many times but it doesen´t work.
This is my code
<!DOCTYPE html>
<html>
<head>
<title>Península</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<script src='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/leaflet.markercluster.js'></script>
<script src="leaflet.markercluster.layersupport-src.js"></script>
<script>
var NemachIcons =L.Icon.extend({
options:{
shadowUrl:'',
iconSize: [50,55],
iconAnchor: [45,45],
popupAnchor:[-3,-76]
}
});
var tiloIcon = new NemachIcons({iconUrl:'http://www.iconshock.com/img_jpg/SIGMA/general/jpg/256/pyramid_icon.jpg'}),
puebloIcon = new NemachIcons({iconUrl:'http://icons.iconseeker.com/png/fullsize/gant/pointless-bw-circle-i-use-it-iex.png'}),
gasIcon =new NemachIcons({iconUrl:'https://cdn2.iconfinder.com/data/icons/function_icon_set/circle_green.png'});
L.icon =function (options) {
return new L.Icon(options);
};
var sitios = new L. LayerGroup();
L.marker([20.683, -88.568], {icon: tiloIcon}).bindPopup('1').addTo(sitios),
L.marker([21.204547, -89.269466], {icon: tiloIcon}).bindPopup('2').addTo(sitios),
L.marker([20.332362, -89.647899], {icon: tiloIcon}).bindPopup('3').addTo(sitios),
L.marker([20.486417, -88.660218], {icon: tiloIcon}).bindPopup('4').addTo(sitios),
L.marker([21.151196, -87.958143], {icon: tiloIcon}).bindPopup('5').addTo(sitios);
var pueblo = new L.LayerGroup();
L.marker([20.9330, -89.0178], {icon: puebloIcon}).bindPopup('6').addTo(pueblo),
L.marker([20.6909, -88.2015], {icon: puebloIcon}).bindPopup('7').addTo(pueblo);
var gas = new L.LayerGroup();
L.marker([20.973907, -89.578931], {icon: gasIcon}).bindPopup('8').addTo(gas);
var mbAttr = ' ' +
'' +
'',
mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw';
var grayscale = L.tileLayer(mbUrl, {id: 'mapbox.light', attribution: mbAttr}),
streets = L.tileLayer(mbUrl, {id: 'mapbox.streets', attribution: mbAttr});
var map = L.map('map', {
center: [20.794527, -88.760612],
zoom: 8,
layers: [grayscale, sitios]
});
var baseLayers = {
//"Grayscale": grayscale,
//"Streets": streets
};
var overlays = {
"Pirámide": sitios,
"Poblado": pueblo,
"Servicio": gas
};
L.control.layers(baseLayers, overlays).addTo(map);
</script>
</body>
</html>
I´ll appreciate all your answers
Like for Leaflet.markercluster, you have to create a Marker Cluster Group where your sub-groups will go into.
In the case of Layer Support, you create a Marker Cluster Group with Layer Support instead:
var mcg = L.markerClusterGroup.layerSupport().addTo(map);
Then you "check in" the sub-groups, so that they know they have to go into that clustering group rather than directly to the map, when they are selected through the Layers Control:
mcg.checkIn([
sitios,
pueblo,
gas
]);
Demo: http://plnkr.co/edit/CT3E63AKWze34FqUoiHn?p=preview
Note: you should download the JavaScript file leaflet.markercluster.layersupport-src.js, if not already done, and place it next to your HTML page, so that it can refer to it locally.
Note 2: if your usage requires only compatibility of clustering with L.Control.Layers, you might be interested in this more simple plugin: Leaflet.FeatureGroup.SubGroup.
Disclaimer: I am the author of these plugins.

Categories

Resources