Polygon from LeafletDraw to GeoJSON - javascript

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.

Related

WMTS displaying emty tiles in leaflet js

I'm using leaflet js and lantmateriet api for displaying map. But the map displaying empty white tiles in the browser. Map displaying fine with other api's like OSM. Im getting problem with lantmateriet api. This is my code.
var mapOptions = {
center: [59.4022, 13.5115],
zoom: 4
}
var map = new L.map('map', mapOptions);
L.tileLayer('https://api.lantmateriet.se/open/topowebb-ccby/v1/wmts/token/apikey/1.0.0/topowebb/default/3006/{z}/{y}/{x}.png', {
attribution: ''
}).addTo(map);
var marker = L.marker([59.3293, 18.0686]).addTo(map);
var m2 = L.marker([59.9139, 10.7522]).addTo(map);
m2.bindPopup("Oslo").addTo(map);
marker.bindPopup('Stockholm').addTo(map);
var latlngs = [
[59.9139, 10.7522],
[59.4022, 13.5115],
[59.3293, 18.0686]
];
var polyline = L.polyline(latlngs, {
color: 'red'
});
polyline.addTo(map);
var circleCenter = [59.4022, 13.5115]; // Center of the circle
var circleOptions = {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
}
// Creating a circle
var circle = L.circle(circleCenter, 10000, circleOptions);
circle.addTo(map); // Adding circle to the map
<!DOCTYPE html>
<html>
<head>
<title>Leaflet sample</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id="map" style="width: 900px; height: 580px"></div>
</body>
</html>
Please help me to solve this problem. Thanks in advance.
It seems you have a problem with authentication to lantmateriet (all requests get a 401 return code), I didn't see anywhere a token for authentication.
I think you have to check that first.

Return canvas (image) in openlayers 4

the example shows how to bind a button click event to the canvas and then it returns the image Example. How can I change it, that when I use a call openlayers with a permalink, that it automatically returns me that image? I would like to use a simple get request from an c++ programm to get the image. I have the
e.g. "#map=12/1085115.28/6035092.46/0" as parsing parameters. Any ideas?
Thanks and Greetings
Melina
So far I have the parameter parsing
<!DOCTYPE html>
<html>
<head>
<title>OpenStreetMap</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.2.0/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.2.0/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var center = [0,0];
var zoom = 0;
var rotation = 0;
if (window.location.has !== '')
{
var hash = window.location.hash.replace('#map=', '');
var parts = hash.split('/');
console.log (parts);
if (parts.length === 4)
{
zoom = parseInt(parts[0],10);
center = [
parseFloat(parts[1]),
parseFloat(parts[2])
];
rotation = parseFloat(parts[3]);
var rotation = 0;
}
}
var openStreetMapLayer = new ol.layer.Tile({
source: new ol.source.OSM({
attributions: [
'All maps © openStreetMapLayer',
ol.source.OSM.ATTRIBUTION
],
opaque: false,
// url: '<myosmserver>/hot/{z}/{x}/{y}.png'
})
});
var map = new ol.Map({
layers: [
openStreetMapLayer
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
maxZoom: 20,
center: center,
zoom: zoom
})
});
</script>
</body>
</html>
You cannot add a link that will somehow download the map as an image. You will need to render it somewhere.
This is how it works. When Openlayers renders the map, it renders it in a HTML canvas element. The download feature is not a Openlayers feature but a HTML canvas feature. The canvas has API to take a snapshot of the current canvas. You can download it as an image.
You can either render the map in a browser or render it server-side. I have not tried rendering the Openlayers map on the server but it should be possible.

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);

Leaflet : Function to initialize map container

Have the latitude and longitude of various places in a html table, on clicking the row,a function sends the latitude and longitude values to a javascript function which loads the openstreetmap map and marker in a bootstrap modal.
This works the first time the function is called, the marker is shown but on closing the modal and the function is called again I get the error
Uncaught Error: Map container is already initialized.
function sendlatlng(id) {
var geom=document.getElementById('cor'+id).value;
var geom1=document.getElementById('cod'+id).value;
var map = L.map(('map'),{scrollWheelZoom:true}).setView([geom,geom1], 12);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
maxZoom: 18
}).addTo(map);
L.marker([geom,geom1]).addTo(map);
}
Is there a way that the map div
<div id="map" class="map" style="height: 300px;"></div>
Is re initialized every time the modal is opened or the function is called.
The error coming from leaflet because we are trying to create a map container each time sendlatlng is executed. That's ok, because instead of trying to create the map and marker in the sendlatlng function, we can create those once, and then use the function to update the coordinates of the existing objects. Here is an example:
<html>
<head>
<title>A Leaflet map!</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js"></script>
<style>
#map {
width: 450px;
height: 250px
}
</style>
</head>
<body>
<div id="map"></div>
<script>
//just for the demo
var defaultCoords = [-41.291, -185.229];
//set up our map
var map = L.map('map').setView(defaultCoords, 12);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
maxZoom: 18
}).addTo(map);
//this is how we are going to demo our sendlatlng function
map.on('click', onMapClick);
//use this variable to track our marker here outside of the sendlatlng function
var myMarker = L.marker(defaultCoords).addTo(map);
//in our example, we are going to listend for clicks on the map to trigger
//changes to the coords with our sendlatlng function
function onMapClick(e) {
sendlatlng(e.latlng)
}
//update the map and marker positions based on the coords passed to the function
//we will just update our existing map and myMarker variables instead of create new ones
function sendlatlng(coords) {
map.setView(coords, 12);
myMarker.setLatLng(coords);
}
</script>
</body>
</html>
In the demo, we are triggering the sendlatlng function with a mouse click on the map. This will recenter the map and move myMarker to the new center.
If, for example, you wanted to create a new marker in the click location, we could do that the same way you originally had your function: by adding a new marker: L.marker(coords).addTo(map);
If you create a map and try to map it again, you'll get this error. Try the following sample codes
//Use this before creating the map
if (map != undefined) {
map.remove();
}
//Use this after adding tile layer
setTimeout(function () { map.invalidateSize() }, 1200);

Connect dynamic data with google marker

I want to connect my dynamic data with google map marker here is my code
this is my mapdata and listdata both having same value which coming from the php
latitude: "19.1904917"
logitude: "72.8639419"
name: "Monkey d luffy"
using this latitude and logitude i m showing google marker on map for show marker data i used this code
var defaultLatlng = new google.maps.LatLng(19.0822508,72.8812041);
var myOptions = {
zoom: 10,
panControl:false,
streetViewControl:false,
center: defaultLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl:true,
zoomControlOptions: {
style:google.maps.ZoomControlStyle.SMALL
},
};
loadMap();
function loadMap(){
console.log('loadMap');
// create new map make sure a DIV with id myMap exist on page
map = new google.maps.Map(document.getElementById("myMap"), myOptions);
geocoder = new google.maps.Geocoder();
//oms = new OverlappingMarkerSpiderfier(map,{markersWontMove: true, markersWontHide: true});
// create new info window for marker detail pop-up
$.each(mapdata.locations,function(key,val){
loadMarker(val);
});
$.each(listdata.locations,function(key,val){
loaddata(val);
});
}
this is my loadmarker function which showing marker on google maps
function loadMarker(markerData)
{
var myLatlng = new google.maps.LatLng(markerData['latitude'],markerData['logitude']);
console.log(myLatlng);
// create new marker
var marker = new google.maps.Marker({
map: map,
title: markerData['address'],
position: myLatlng
//animation:google.maps.Animation.BOUNCE
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
gmarkers.push(marker);
var marker_num = gmarkers.length-1;
google.maps.event.addListener(marker, 'click', function() {
showMarker(markerData,marker);
});
}
this is my loaddata function which is showing my data on UI
function loaddata(markerData)
{
listitem += "<div class='expert_name'>"
+markerData['name']+
+"</div>"
$('#_mymaplist').html(listitem);
}
this is my html where i add all this thing
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Multiple Markers Google Maps</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="mymap" style="width: 800px; height:500px;"></div>
<div id="_mymaplist" style="width: 800px; height:500px;"></div>
</body>
</html>
i want when i hover name from _mymaplist div then google marker color has to change for the example here i only give one data but there will be more than one
i checked many example like this but i won't work for me
because this example having same function for loading the data..but in my case i have 2 function to load data. i also can use 1 function but problem is that map marker loading all data at one time and the list data is using pagination form loading data....so that y i can't use same function for loading data Please help me
Because of the issue of pagination if you have to use 2 functions, you can use the Styled Marker in the loaddata() function itself where you are defining your individual markers. For that you will need to use set(property, value) methods.
this.styleIcon.set('color', '00fff0');
This has to be defined inside your loaddata() function where your listitems are initialized.
function createStyle() { return new StyledIcon(StyledIconTypes.BUBBLE,{color:"#95AA7B",text:"click me!",fore:"#ffffff"}); }
listitem += "<div class='expert_name'>"
+markerData['name']+
+"</div>"
$('#_mymaplist').html(listitem);
google.maps.event.addDomListener(marker4,"click", function(o){
this.styleIcon.set("fore","#ffffff");//test color
this.styleIcon.set("color","#C2554D");// background color
this.styleIcon.set("text","color changed");
});
Hope this would Help!!

Categories