Can someone translate this google.api to a leaflet script? - leaflet

I want to have this script useable for the leaflet libary to use openstreetmap.
I need a dragable marker which stores it coordinates and on dragend sends it to a hidden form which will be sent to my sqlite database!
im not so good in codeing! help much appreciated
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: mapCenter,
title: markerTitle,
icon: markerImage
});
google.maps.event.addListener(marker, 'dragend', function() {
updateLatLong();
});
google.maps.event.addListener(map, 'click', function(event) {
var myLatLng = event.latLng;
var markerPosition = new google.maps.LatLng(myLatLng.lat(), myLatLng.lng());
marker.setPosition(markerPosition);
updateLatLong();
});
updateLatLong();
}
function updateLatLong() {
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
document.getElementById("nexthh_latitude").value = lat;
document.getElementById("nexthh_longitude").value = lng;
}

It should be something like
var map = L.map();//Set your map options
markerImage = L.icon.Default(); //Change this with your icon options.
var marker = L.marker({
draggable:true,
position: map.getCenter(),
title: markerTitle,
icon: markerImage
});
marker.addTo(map);
marker.on('dragend',function() {
updateLatLong();
});
map.on('click',function(event) {
marker.setLatLng(event.latLng);
updateLatLong();
});
function updateLatLong() {
var lat = marker.getLatLng().lat;
var lng = marker.getLatLng().lng;
document.getElementById("nexthh_latitude").value = lat;
document.getElementById("nexthh_longitude").value = lng;
}
Lealfet has an excellent docs here http://leafletjs.com/reference.html

thx for the help!
i wrote it like this:
var map = L.mapbox.map('map', 'examples.map-9ijuk24y')
.setView([48.20682894891699, 16.370315551757812], 12);
var marker = L.marker([48.20682894891699, 16.370315551757812],{
draggable: 'true',
}).addTo(map);
marker.on('dragend', function(event) {
var marker = event.target;
var lat = marker.getLatLng().lat;
var lon = marker.getLatLng().lng;
document.getElementById("latitude").value = lat;
document.getElementById("longitude").value = lon;
});

Related

Leaflet error when zoom after close popup

I created a map and added markers on it in salesforce lightning component ,
issue is:
click on marker >> click on map (this close the popup) >> zoom in and out >> this error displayed for each zoom step:
Uncaught TypeError: Cannot read property '_latLngToNewLayerPoint' of
null throws at /resource/1498411629000/leaflet/leaflet.js:9:10763
this is the code in component javascript helper:
({
drawMap: function(component,map){
var mapElement = component.find("map").getElement();
map = L.map(mapElement).setView([35.232, 40.5656], 12);
L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
{
attribution: 'Tiles © Esri'
}).addTo(map);
var markers = L.marker([35.232, 40.5656]).addTo(map);
component.set("v.map", map);
component.set("v.markers", markers);
},
putMarkers: function(component) {
var map = component.get('v.map');
var markers = component.get('v.markers');
var projects = component.get('v.projects');
var projectsAction = component.get("c.getProjectsList");
var markerArray = [];
var symbol;
var symbol1 = 'symbolURl';
var symbol2 = 'symbolURl';
projectsAction.setCallback(this, function(response) {
var state = response.getState();
if( state == "SUCCESS"){
projects = response.getReturnValue();
if (markers) {
markers.remove();
}
// Add Markers
if (map && projects && projects.length> 0) {
for (var i=0; i<projects.length; i++) {
var project = projects[i];
if (project.Latitude && project.Longitude) {
var latLng = [project.Latitude, project.Longitude];
var currentStatus = project.status;
if(currentStatus=="status1")
symbol = symbol1;
else if(currentStatus=="status2")
symbol = symbol2;
var popupTemplate = '<b style="color:black; font-size:11px;">Project Name:</b><span style="float:right;margin-right:10px;color:#800000;font-size:11px;width:110px;text-align:right; white-space:normal;" > '+project.name;
var icon = new L.DivIcon({
className:'',
html: '<img style="width:34px;height:37px;" src="'+symbol+'"/>'+
'<span style="font-weight:bold;font-size:9pt;">text</span>'
});
var marker = L.marker(latLng, {project: project,icon:icon,title:project.name}).bindPopup(popupTemplate,{minWidth:200});
markerArray.push(marker);
}
}
L.layerGroup(markerArray).addTo(map);
component.set("v.map", map);
}}
else if(state == "ERROR"){
console.log('Error in calling server side action');
}
});
$A.enqueueAction(projectsAction);
}
and in javascript controller:
jsLoaded: function(component, event, helper) {
var map = component.get("v.map");
if (!map) {
helper.drawMap(component,map);
helper.putMarkers(component);
}
},
projectsChangeHandler: function(component, event, helper) {
helper.putMarkers(component);
}
where is the problem? please help
this is a new bug for Vue3,I've solved it:
change Proxy'map to toRaw(map),like this:
L.geoJSON(geoJson, {
style: {
color: '#ff0000',
fillColor: "#ff000000",
weight: 1
},
onEachFeature: myonEachFeature,
}).addTo(toRaw(map))
I solved it by editing the leaflet.js file:
search for the word ( _latLngToNewLayerPoint )
and wrap the code with the condition:
if(this._map)
so if _map is null, skip
I don't know why this bug is only presented in salesforce
In my case it was related to the framework variable wrappers (vue.js).
When I use observable variable like this:
data() {
return {
map: null,
};
},
mounted() {
// here it's required to use a global variable
// or a variable without framework handlers
// map = L.map(...);
this.map = L.map('map', { preferCanvas: true }).setView([51.505, -0.09], 13);
}
I get error:
Popup.js:231 Uncaught TypeError: Cannot read property '_latLngToNewLayerPoint' of null
at NewClass._animateZoom (Popup.js:231)
at NewClass.fire (Events.js:190)
at NewClass._animateZoom (Map.js:1689)
at NewClass.<anonymous> (Map.js:1667)
The solution is just to define the map variable outside of framework, in other words use a global variable for leaflet structures.

leaflet marker dragging moves map

I am working on OSM using leaflet..I enable dragging:true on my destination marker as I need it to be draggable ,but while dragging marker my MAP also moves .Is there a way I can only move the marker.
$(document).ready(function()
{
homepg();
});
var cab_map = null;
function homepg()
{
var str = '';
var markers = new L.MarkerClusterGroup();
var lat = '19.068246';
var lng = '72.850638';
cab_map = ddmap.init('mapdivcab',[lat,lng],14);
ddmap.getDirection(13.039680,77.580214,13.040850,77.625532,cab_map,'lmenu');
}
getDirection: function(flat,flon,tlat,tlon,map,mapdv)
{
this.dirMap = map;
this.mapDiv = mapdv;
this.sourceLatLng = new L.LatLng(flat,flon);
this.targetLatLng = new L.LatLng(tlat,tlon);
if(this.fScript)
head.removeChild(fScript);
fScript = document.createElement('script');
fScript.setAttribute("type","text/javascript");
fScript.setAttribute("src", ddmap.serverUrl+"jsonp=ddmap.updateAddressFrom/nearbylocation/"+flat.toFixed(6).replace('.','')+"/"+flon.toFixed(6).replace('.','')+"/1?json_callback=%jsonp");
document.getElementsByTagName("head")[0].appendChild(fScript);
if(this.tScript)
head.removeChild(tScript);
tScript = document.createElement('script');
tScript.setAttribute("type","text/javascript");
tScript.setAttribute("src", ddmap.serverUrl+"jsonp=ddmap.updateAddressTo/nearbylocation/"+tlat.toFixed(6).replace('.','')+"/"+tlon.toFixed(6).replace('.','')+"/1?json_callback=%jsonp");
document.getElementsByTagName("head")[0].appendChild(tScript);
if(this.currentScript)
head.removeChild(currentScript);
currentScript = document.createElement('script');
currentScript.setAttribute("type","text/javascript");
currentScript.setAttribute("src", "viaroute?z=13&output=json&jsonp=ddmap.showRoute&loc="+flat+","+flon+"&loc="+tlat+","+tlon+"&instructions=true");
document.getElementsByTagName("head")[0].appendChild(currentScript);
}
showRoute: function(response) {
var geometry = this._decode(response.route_geometry, 6);
var route = new L.Polyline( [], {dashArray:""} );
route.setLatLngs( geometry );
var sIcon = L.icon({iconUrl:this.imageHost+"/images/marker-source.png",iconAnchor:[10,30],shadowUrl: this.imageHost+'/images/marker-shadow.png'});
var tIcon = L.icon({iconUrl:this.imageHost+"/images/marker-target.png",iconAnchor:[10,30],shadowUrl: this.imageHost+'/images/marker-shadow.png'});
mrkrSrc = L.marker(this.sourceLatLng, {icon: sIcon});
mrkrTgt = L.marker(this.targetLatLng, {icon: tIcon,draggable:'true'});
if(this.mainLayer)
this.dirMap.removeLayer(this.mainLayer);
this.mainLayer = L.layerGroup([mrkrSrc, mrkrTgt])
.addLayer(route)
.addTo(this.dirMap);
var bounds = new L.LatLngBounds(this.sourceLatLng, this.targetLatLng);
this.dirMap.fitBounds(bounds);
this.showRouteDesc(response,geometry);
//
mrkrTgt.on('drag', function(event){
var marker = event.target;
var dst = marker.getLatLng();
var src = mrkrSrc.getLatLng();
ddmap.getroute(src.lat,src.lng,dst.lat,dst.lng,cab_map,'lmenu');//instead of calling getDriection i m calling this function
});
//this function is same as getDirection but i have removed some code, thought that is not required and it was making 'drag event' rough and time taking
getroute: function(flat,flon,tlat,tlon,map,mapdv)
{
this.dirMap = map;
this.mapDiv = mapdv;
this.sourceLatLng = new L.LatLng(flat,flon);
this.targetLatLng = new L.LatLng(tlat,tlon);
if(this.currentScript)
head.removeChild(currentScript);
currentScript = document.createElement('script');
currentScript.setAttribute("type","text/javascript");
currentScript.setAttribute("src", "viaroute?z=13&output=json&jsonp=ddmap.showRoute&loc="+flat+","+flon+"&loc="+tlat+","+tlon+"&instructions=true");
document.getElementsByTagName("head")[0].appendChild(currentScript);
}

Automatically Zoom the map to fit all markers

Following an example, you can see the plunker her http://plnkr.co/edit/lJHyP3dhT3v8aHVdt3D3?p=preview
Regardless of whatever zoom value is provided while initializitng the map, I want to zoom the map automatically so all the markers are inside the view. Here is my code
var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© OpenStreetMap contributors, Points &copy 2012 LINZ'
}),
latlng = L.latLng(-37.82, 175.24);
var map = L.map('map', {center: latlng, zoom: 10, layers: [tiles]});
var markers = L.markerClusterGroup();
for (var i = 0; i < addressPoints.length; i++) {
var a = addressPoints[i];
var title = a[2];
var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
marker.bindPopup(title);
markers.addLayer(marker);
}
map.addLayer(markers);
var group = new L.featureGroup(markers);
map.fitBounds(group.getBounds());
You need to
create an array
push all your markers in array
once all the markers are added to array, create a featureGroup
add your markers array to featureGroup and then zoom to its bounds.
Below is the modified code
var markerArray = []; //create new markers array
for (var i = 0; i < addressPoints.length; i++) {
var a = addressPoints[i];
var title = a[2];
var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
marker.bindPopup(title);
markers.addLayer(marker);
markerArray.push(marker); //add each markers to array
if(i==addressPoints.length-1){//this is the case when all the markers would be added to array
var group = L.featureGroup(markerArray); //add markers array to featureGroup
map.fitBounds(group.getBounds());
}
}
Here is the working plunk

Leaflet : Map container is already initialized

The User types some address (Hyderabad,Telanagna) on text field and clicks on Go button
I am fetching the latitude_res and longitude from google Map API as shown below
$(document).on('click', '.gobtn', function(event) {
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '', function(data) {
latitude_res = data.results[0].geometry.location.lat;
longitude_res = data.results[0].geometry.location.lng;
}).done(function() {
});
});
I am able to fetch the latitude and longitude , from google API say for example i got the following values
**17.385044
78.910965**
Then i am making a Ajax call again to fetch all the Markers present at this location in our Database .
And finally initializaing the map as shown below
initializeMap(lator,lonor,markers);
function initializeMap(lator, lonor, markers) {
var map = new L.Map('map_canvas', {
center: new L.LatLng(lator, lonor),
zoom: 5
});
var ggl = new L.Google();
var ggl2 = new L.Google('ROADMAP');
map.addLayer(ggl2);
if (markers.length > 0) {
var markers_leafcontainer = new L.MarkerClusterGroup();
var markersList = [];
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].latitude);
var lng = parseFloat(markers[i].longititude);
var trailhead_name = markers[i].address;
var dealerId = markers[i].dealerID_db;
var dealername = markers[i].dealerName_db;
var contentString = "<html><body><div><p><h2>" + dealername + "</h2></p></div></body></html>";
var marker = L.marker(new L.LatLng(lat, lng), {}).on('click', onClick);
$(".howmanyfound").text(markers.length + ' Found');
markers_leafcontainer.addLayer(marker);
}
map.addLayer(markers_leafcontainer);
map.fitBounds(markers_leafcontainer.getBounds()); //set view on the cluster extent
}
}
Only for the first time this is working , from there on i am getting Uncaught Error: Map container is already initialized.
I am using leaflet with google Maps
So, don't initialize the map inside your function.
var map = new L.Map('map_canvas');
initializeMap(lator,lonor,markers);
function initializeMap(lator, lonor, markers) {
map.setView(L.latLng(lator, lonor));
}

Integrating / adding Google Earth View to my map

I am creating an interactive map for a non profit association "Friends of Knox Mountain Park" but I am getting trouble with the Google Earth view.
I've been searching on the web for weeks and none of the solutions I found works for me. Can someone take a look of the code and let me know what I should do to include Google Earth View in the map? Thanks in advance.
The online project: http://www.virtualbc.ca/knoxmountain/
And this is the javascript file (mapa2.js) containing the google map's code:
google.load('earth', '1');
var map;
var googleEarth;
var gmarkers = [];
var iconShadow = new google.maps.MarkerImage('icons/shadow.png',
new google.maps.Size(46, 42),
new google.maps.Point(0,0),
new google.maps.Point(13, 42));
var sites = [
['Apex Trail - Shelter',49.91174271, -119.48507050, 4, '<img src="images/apex_point_high.jpg">','magenta','14'],
['Apex Trail',49.91286999, -119.48413424, 3, '<img src="images/apex_point_low.jpg">','lemon','1'],
['Gordon Trail',49.91971281, -119.47954356, 2, '<img src="images/apex_point_low.jpg">','lemon','1'],
['Paul Tomb Bay',49.92555541, -119.47710250, 1, '<img src="images/tomb_bay.jpg">','lemon','1']
];
var infowindow = null;
var overlay;
// Used to make Google Map quard coords to MapCruncher/BingMaps quard coords
function TileToQuadKey ( x, y, zoom)
{
var quad = "";
for (var i = zoom; i > 0; i--)
{
var mask = 1 << (i - 1);
var cell = 0;
if ((x & mask) != 0)
cell++;
if ((y & mask) != 0)
cell += 2;
quad += cell;
}
return quad;
}
function init() {
var centerMap = new google.maps.LatLng(49.909671, -119.482241);
var myOptions = {
zoom: 10,
center: centerMap,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Create the tile layers
// ASTER Tile Layer
myASTEROptions = {
getTileUrl : function (a,b) {
return "http://www.virtualbc.ca/knoxmountain/map/" + TileToQuadKey(a.x,a.y,b) + ".png";
},
isPng: true,
opacity: 1.0,
tileSize: new google.maps.Size(256,256),
name: "ASTER",
minZoom:13,
maxZoom:20
}
ASTERMapType = new google.maps.ImageMapType( myASTEROptions );
map.overlayMapTypes.insertAt(0, ASTERMapType);
// Aerial Tile Layer
myAerialOptions = {
getTileUrl : function (a,b) {
return "http://www.virtualbc.ca/knoxmountain/map/" + TileToQuadKey(a.x,a.y,b) + ".png";
},
isPng: true,
opacity: 1.0,
tileSize: new google.maps.Size(256,256),
name: "Aerial",
minZoom:15,
maxZoom:21
}
AerialMapType = new google.maps.ImageMapType( myAerialOptions );
map.overlayMapTypes.insertAt(1, AerialMapType);
var panorama = new google.maps.StreetViewPanorama(map.getDiv());
panorama.setVisible(false);
panorama.set('enableCloseButton', true);
map.setStreetView(panorama);
panorama.setPosition(centerMap);
setMarkers(map, sites);
setZoom(map, sites);
infowindow = new google.maps.InfoWindow({
content: "Loading..."
});
googleEarth = new GoogleEarth(map);
google.maps.event.addListenerOnce(map, 'tilesloaded', addOverlays);
}
/*
This functions sets the markers (array)
*/
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var site = markers[i];
var siteLatLng = new google.maps.LatLng(site[1], site[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: site[0],
zIndex: site[3],
html: site[4],
// Markers drop on the map
animation: google.maps.Animation.DROP,
icon: 'http://www.virtualbc.ca/knoxmountain/icons/icon.png',
shadow: iconShadow
});
gmarkers.push(marker);
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
/*
Set the zoom to fit comfortably all the markers in the map
*/
function setZoom(map, markers) {
var boundbox = new google.maps.LatLngBounds();
for ( var i = 0; i < markers.length; i++ )
{
boundbox.extend(new google.maps.LatLng(markers[i][1], markers[i][2]));
}
map.setCenter(boundbox.getCenter());
map.fitBounds(boundbox);
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i-1], "click");
}
google.maps.event.addDomListener(window, 'load', init);
The first issue I notice with your site is you are linking to http://www.virtualbc.ca/src/googleearth-compiled.js which does not exist.