Label for Leaflet Polylines - javascript

I want to show label/Text with polylines, Here is my code
function displayDottedLine(latA, longA, latB, longB, label) {
var pointA = new L.LatLng(latA, longA);
var pointB = new L.LatLng(latB, longB);
var pointList = [pointA, pointB];
var firstpolyline = new L.Polyline(pointList, {
color: 'white',
weight: 1.5,
opacity: 0.5,
dashArray: "10 10",
smoothFactor: 1
});
firstpolyline.addTo(map);
}
there is label parameter in the function, i need to attach this label with polylines.
Thanks in advance.

You can try leaflet.textpath.js plugin
window.addEventListener('load', function() {
var map = L.map('map').setView([51.328125, 42.2935], 18);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var plane = L.polyline([
[3.33984375, 46.6795944656402],
[29.53125, 46.55886030311719],
[51.328125, 42.293564192170095],
]).addTo(map);
map.fitBounds(plane.getBounds());
plane.setText('SAMPLE TEXT', {center: true});
});
#map {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-textpath#1.2.0/leaflet.textpath.min.js"></script>
<div id="map"></div>

Related

Hover over Element in Custom Leaflet Legend

I created a Leaflet Map with a Legend. The goal would be to hover over the text element in the legend area and show a tooltip with a image.
Problem: hover is not showing up! I tried very different version. The easiest way which should usually work is this one:
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'}).addTo(map);
var marker = L.marker([51.5, -0.09]).addTo(map).bindPopup('Popup.');
var MyControl = L.Control.extend({
options: {
position: 'topleft'
},
onAdd: function (map) {
// create the control container with a particular class name
var container = L.DomUtil.create('div', 'my-custom-control');
container.innerHTML += '<div id="hoverhelp" title="">Image Hover Example Leaflet</div>';
L.DomEvent.disableClickPropagation(container);
return container;
}});
map.addControl(new MyControl());
$( "#hoverhelp" ).tooltip({ content: '<img src="https://www.google.com/logos/doodles/2020/mascha-kalekos-113th-birthday-6753651837108682-s.png" />' });
If someone wants to try:
jsfiddle
You have to use JQuery UI to get access to tooltip.
https://jqueryui.com/
Here is your code after editing in jsfiddle.
http://jsfiddle.net/2qrbzstu/
// Demo code from leafletjs.com
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var marker = L.marker([51.5, -0.09]).addTo(map).bindPopup('Popup.');
var MyControl = L.Control.extend({
options: {
position: 'topleft'
},
onAdd: function(map) {
// create the control container with a particular class name
var container = L.DomUtil.create('div', 'my-custom-control');
$(container).html('<div id="hoverhelp" title="so how">Image Hover Example Leaflet</div>');
L.DomEvent.disableClickPropagation(container);
return container;
}
});
map.addControl(new MyControl());
$("#hoverhelp").tooltip({ content: '<img src="https://www.google.com/logos/doodles/2020/mascha-kalekos-113th-birthday-6753651837108682-s.png" />' })
#map {
position: fixed;
left:0;
top: 0;
right: 0;
bottom: 0;
}
.my-custom-control {
background-color: white;
padding: 10px;
}
<div id="map" title="map"></div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

How to correctly obtain coordinates from Open Layers v4.2, API when regions repeat

How to correctly obtain coordinates from map when countries repeat, i.e when we zoom out to maximum, countries repeat and clicking on same country gives invalid coordinates. We cannot restrict the user by showing a single world map (this can be done by setting up the WrapX property). Any other solution , Please help.
Adding sample code which displays coordinates. Please hover the mouse over same country/region which repeats and see difference.
"use strict";
var vectorSource = new ol.source.Vector({
wrapX: false
});
/*Layer Styles*/
var stylesIcon = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'icon.png'
})
})
var stylesIcon2 = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0,0,255,0.3)'
}),
stroke: new ol.style.Stroke({
color: '#000100',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#000000'
})
})
})
/*Layers*/
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: stylesIcon
});
/*Map*/
var map = new ol.Map({
layers: [new ol.layer.Tile({
source: new ol.source.OSM({})
}), vectorLayer],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([0, 0]),
zoom: 1
})
});
var element = document.getElementById('popup');
element.onmouseout = function(event) {
element.style.visibility = 'hidden'
};
var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false
});
map.addOverlay(popup);
/*Events*/
map.on("pointermove", function(event) {
var lonlat = ol.proj.transform(event.coordinate, 'EPSG:3857',
'EPSG:4326');
var logitude = lonlat[0];
var lattitude = lonlat[1];
document.getElementById('mousePointer').innerText = 'longitude : ' +
logitude + ' latitude : ' + lattitude;
});
map.on("singleclick", function(event) {
var lonlat = ol.proj.transform(event.coordinate, 'EPSG:3857',
'EPSG:4326');
var logitude = lonlat[0];
var lattitude = lonlat[1];
document.getElementById('mouseClick').innerText = 'longitude : ' +
logitude + ' latitude : ' + lattitude;
});
map.on('click', function(event) {
var feature = map.forEachFeatureAtPixel(event.pixel, function(
feature, layer) {
return feature;
})
if (feature) {
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
popup.setPosition(coord);
var element = document.getElementById('popup');
element.innerText = feature.get('name')
element.style.visibility = 'visible'
}
})
function createMarkers() {
var lat = parseFloat(document.getElementById('latitudeInp').value);
var lng = parseFloat(document.getElementById('logitudeInp').value);
vectorSource.clear();
vectorSource.addFeature(new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([lng, lat],
'EPSG:4326', 'EPSG:3857')),
name: 'Added Marker'
}));
}
a.skiplink {
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
padding: 0;
border: 0;
height: 1px;
width: 1px;
overflow: hidden;
}
a.skiplink:focus {
clip: auto;
height: auto;
width: auto;
background-color: #fff;
padding: 0.3em;
}
#map:focus {
outline: #4A74A8 solid 0.15em;
}
.mapDemo {
border: 1px solid black;
margin-top: 5px;
}
<!DOCTYPE html>
<html>
<head>
<title>Accessible Map</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>
<a class="skiplink" href="#map">Go to map</a>
<div id="map" class="map" tabindex="0"></div>
<div id="mapDemo" class="mapDemo">
<h3>Demo Actions</h3>
<p>
Current mouse pointer : <span id="mousePointer"></span>
</p>
<p>
Clicked at :<span id="mouseClick"></span>
</p>
<p>
Add Marker : <span>
<label>Longitude : </label><input type="number" id="logitudeInp" />
</span> <span>
<label>
Latitude
:
</label><input type="number" id="latitudeInp" />
</span> <span>
<label>
Name
:
</label><input type="text" id="nameInp" />
</span> <span>
<label>
Submit
:
</label><input type="submit" id="submit" onclick="createMarkers()" />
</span>
</p>
</div>
<div id="popup"></div>
</body>
</html>
Set wrapX: false on your tile source.
new ol.layer.Tile({
source: new ol.source.OSM({
wrapX: false
})
})

Google Maps API - Only One JS Script Displays on Map

I answered my question with help from a friend - labels and building polygons with pop ups now display.
The code uses an external GeoJSON with two building coordinates, values for colors and building names. The GeoJSON is used to draw the buidling polygons, and populate infoBox window.
The labels are blank window boxes with coordinates and text hard coded. There are other examples of this on Stack Overflow, however, I was having trouble getting both functions to work. Thanks to everyone who helped.
<!DOCTYPE html>
<html>
<head>
<title>UT Campus Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 90%;
padding: 10px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script>
// global variable
var map;
var mapData;
var dataURL = 'https://googledrive.com/host/0B9SE53Gvj0AsR3hyUDJ4Nk9ybG8/Bld.json';
var infoWindow = new google.maps.InfoWindow();
var colors = ["#9295ca", "#076bb6", "#e66665", "#666", "#333", "#456789"];
// create the map when the page loads
function initialize() {
var mapOptions = {
zoom: 16,
center: new google.maps.LatLng(30.284, -97.7325)
};
// build the map
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// get the data and draw the polygons
$.getJSON( dataURL, function( data ) {
loadGeoJSON(data);
});
// add colors
stylePolygons();
// add click listeners with info boxes
addClickListeners();
// finally add labels
addLabels();
};
// fetch the geojson data from the server
function loadGeoJSON (data) {
console.log(data);
map.data.addGeoJson(data,{idPropertyName:"id"});
};
// assign colors based on value property of each feature
function stylePolygons () {
map.data.setStyle(function(feature) {
var value = feature.getProperty('value');
var color = colors[value];
return {
fillColor: color,
strokeWeight: 1
};
});
};
//listen for click events
function addClickListeners () {
map.data.addListener('click', function(event) {
//show an infowindow on click
infoWindow.setContent('<div style="line-height:1.35;overflow:hidden;white-space:nowrap;"> <b>'+event.feature.getProperty("bldAbbrev") +"</b>"+"</br>" + event.feature.getProperty("GoogInfoWi") +"<br/>" + event.feature.getProperty("addressStr") +"</div>");
var anchor = new google.maps.MVCObject();
anchor.set("position",event.latLng);
infoWindow.open(map,anchor);
});
};
function buildMarkers(map, markerData) {
var newMarkers = [],
marker;
var blankMarker = {
path: 'M 0,0,0 z',
fillColor: 'yellow',
fillOpacity: 0.8,
scale: 0,
strokeColor: 'white',
strokeWeight: 4
};
for(var i=0; i<markerData.length; i++) {
marker = new google.maps.Marker({
map: map,
icon: blankMarker,
draggable: true,
position: markerData[i].latLng,
visible: true
}),
boxText = document.createElement("div"),
//these are the options for all infoboxes
infoboxOptions = {
content: boxText,
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(40, 0),
zIndex: null,
boxStyle: {
background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/examples/tipbox.gif') no-repeat",
opacity: 1,
width: "24px"
},
closeBoxMargin: "12px 4px 2px 2px",
closeBoxURL: "",
infoBoxClearance: new google.maps.Size(0, 0),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
};
newMarkers.push(marker);
//define the text and style for all infoboxes
boxText.style.cssText = "margin-top: 8px; background:#0xFFFFFF; color:#333; font-family:Arial; font-size:24px; padding: 0px; border-radius:0px; -webkit-border-radius:0px; -moz-border-radius:0px;";
boxText.innerHTML = markerData[i].label;
//Define the infobox
newMarkers[i].infobox = new InfoBox(infoboxOptions);
//Open box when page is loaded
newMarkers[i].infobox.open(map, marker);
}
return newMarkers;
};
function addLabels () {
var markerInfoArray =
[
{
latLng: new google.maps.LatLng(30.2848878, -97.7362857),
label:"SAC"
},
{
latLng: new google.maps.LatLng(30.2819835, -97.7404576),
label:"ATT"
}
];
var markerArray = buildMarkers(map, markerInfoArray);
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
I replaced the original question with the working code. Sorry for poor formatting and procedure, this was my first question.

Display google marker on the street view foreground

Is there a way to display the marker icon in fore ground as soon the street view map is loaded, user should not pan until he sees the marker icon, i have updated the code in the below link
var fenway = new google.maps.LatLng(40.729884, -73.990988);
var mapOptions = {
center: fenway,
zoom: 14
};
var map = new google.maps.Map(
document.getElementById('map-canvas'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 500,
pitch: 0
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
var panorama1 = new google.maps.StreetViewPanorama(document.getElementById('pano1'),panoramaOptions);
var marker = new google.maps.Marker({
position:fenway,
map:panorama
});
var marker1 = new google.maps.Marker({
position:fenway,
map:panorama1,
});
map.setStreetView(panorama,fenway);
map.setStreetView(panorama1);
http://jsfiddle.net/vinothpsv/JKx3Z/
The trick is in "google.maps.geometry.spherical.computeHeading"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Street View service</title>
<style>
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry"></script>
<script>
var panorama = null;
var fin;
function initialize() {
//var fenway = new google.maps.LatLng(42.345573,-71.098326);
var fenway = new google.maps.LatLng(40.729884, -73.990988);
var mapOptions = {
center: fenway,
zoom: 14
};
var map = new google.maps.Map(
document.getElementById('map-canvas'), mapOptions);
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'));
panorama.setPosition(fenway);
google.maps.event.addListenerOnce(panorama, 'status_changed', function () {
var heading = google.maps.geometry.spherical.computeHeading(panorama.getLocation().latLng, fenway);
panorama.setPov({
heading: heading,
pitch: 0
});
setTimeout(function() {
marker = new google.maps.Marker({
position: fenway,
map: panorama,
});
if (marker && marker.setMap) marker.setMap(panorama);}, 500);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 400px; height: 300px"></div>
<div id="pano" style="position:absolute; left:410px; top: 8px; width: 400px; height: 300px;"></div>
<div id="pano1" style="position:relative; left:410px; top: 8px; width: 400px; height: 300px;"></div>
</body>
</html>
Sounds like you just want to change the heading... Not sure what you want. The marker is based on where the heading is.

Display world map with no repeats

I'm currently using the Google Maps API for the first time.
Essentially I wish to have the map zoomed out so that the whole world is displayed with no overlap (e.g. bits of a certain country are not repeated on either side of the map).
The closest I have found to my requirements is this SO question:
Google Maps API V3: Show the whole world
However, the top answer on this question does not provide the full code required.
I have used the starter example from Google as the base for my HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCuP_BOi6lD7L6ZY7JTXRdhY1YEj_gcEP0&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 1
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
However, in the example provided in the question above a number of additional variables have been specified. My question is, where do I plug in the code from the question above to ensure that my world map is displayed correctly?
If you don't want any repeats, you need to control the minimum zoom allowed and the width of your map to be less than or equal to one width of of the base tiles at the minimum zoom level allowed on your map.
At zoom zero, one width of the world is a single 256 x 256 pixel tile, each zoom level increases that by a factor of 2.
This will show one width of the map at zoom level 1 (512x512 map-canvas), you can change the height, but the width will need to be 256 at zoom 0, 512 at zoom 1, 1024 at zoom 2, etc:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 512px; width:512px;}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 1,
minZoom: 1
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
code snippet:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 1,
minZoom: 1
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map-canvas {
height: 512px;
width: 512px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>
Here's a function worldViewFit I like to use:
function initMap() {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
minZoom: 1
};
map = new google.maps.Map(document.getElementById('officeMap'), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
//Map is ready
worldViewFit(map);
});
}
function worldViewFit(mapObj) {
var worldBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(70.4043,-143.5291), //Top-left
new google.maps.LatLng(-46.11251, 163.4288) //Bottom-right
);
mapObj.fitBounds(worldBounds, 0);
var actualBounds = mapObj.getBounds();
if(actualBounds.getSouthWest().lng() == -180 && actualBounds.getNorthEast().lng() == 180) {
mapObj.setZoom(mapObj.getZoom()+1);
}
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#officeMap {
height: 512px;
width: 512px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="officeMap"></div>
This is the JavaScript I found:
/**
* All locations map scripts
*/
jQuery(function($){
$(document).ready(function(){
loadmap();
});
function loadmap()
{
var locations = wpsl_locator_all.locations;
var mapstyles = wpsl_locator.mapstyles;
var mappin = ( wpsl_locator.mappin ) ? wpsl_locator.mappin : '';
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap',
mapTypeControl: false,
zoom: 8,
styles: mapstyles,
panControl : false
}
if ( wpsl_locator.custom_map_options === '1' ) mapOptions = wpsl_locator.map_options;
var infoWindow = new google.maps.InfoWindow(), marker, i;
var map = new google.maps.Map( document.getElementById('alllocationsmap'), mapOptions );
// Loop through array of markers & place each one on the map
for( i = 0; i < locations.length; i++ ) {
var position = new google.maps.LatLng(locations[i].latitude, locations[i].longitude);
bounds.extend(position);
var marker = new google.maps.Marker({
position: position,
map: map,
title: locations[i].title,
icon: mappin
});
// Info window for each marker
google.maps.event.addListener(marker, 'click', (function(marker, i){
return function() {
infoWindow.setContent(locations[i].infowindow);
infoWindow.open(map, marker);
wpsl_all_locations_marker_clicked(marker, infoWindow)
}
})(marker, i));
// Center the Map
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
if ( locations.length < 2 ) {
map.setZoom(13);
}
google.maps.event.removeListener(listener);
});
}
// Fit the map bounds to all the pins
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
google.maps.event.removeListener(boundsListener);
});
wpsl_all_locations_rendered(map);
} // loadmap()
});

Categories

Resources