I can make clickable country labels but get error when I click anywhere else - mapbox

I am trying to create a pop when the user clicks the country label. My code accomplishes this but if the user accidentally clicks anywhere else I get the error "TypeError: Cannot read property 'properties' of undefined". Any help would be appreciated. Thanks.
export default class App extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
lng: -32.87393,
lat: 43.6439,
zoom: 3,
mxZoom: 7,
};
this.mapContainer = React.createRef();
}
componentDidMount() {
const { lng, lat, zoom , mxZoom} = this.state;
const map = new mapboxgl.Map({
container: this.mapContainer.current,
style: 'mapbox://styles/chriswade112358/ckpipp5el0jky18qwzep8ppyl',
center: [lng, lat],
zoom: zoom,
minZoom: zoom,
maxZoom: mxZoom,
});
map.on('style.load', function() {
map.on('click', function(e) {
const features = map.queryRenderedFeatures(e.point, { layers: ['country-label'] });
new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML('you clicked here: <br/>' + features[0].properties.name)
.addTo(map);
});
});
}

Related

How to stop cursor flickering over mapbox marker icons?

How do I stop cursor flickering over my Mapbox icons? Here is the live site where you can see the problem when hovering over the marker icons: https://rustic-waters-group.thesparksite.com/lakes/
Here is my code:
mapboxgl.accessToken = 'pk.eyJ1IjoiZG1pdHJpbWFydGluIiwiYSI6ImNreHRobHRmcjVqM3cydmt5NWkxdWNibTcifQ.CuN5Dwc963TW-BKRcowxBA';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/dmitrimartin/ckxtj5aur4fvv15mrhmihala8',
center: [-89.2, 44.33],
zoom: 9.2
});
map.on('load', () => {
const popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
map.on('mouseenter', 'lakes', (event) => {
map.getCanvas().style.cursor = 'pointer';
const features = map.queryRenderedFeatures(event.point, {
layers: ['lakes']
});
if (event.features.length === 0) return;
popup.setLngLat(features[0].geometry.coordinates);
popup.setHTML('<h3 class="lake-popup">' + features[0].properties.title + '</h3>');
popup.setMaxWidth("calc(100vw - 40px);");
popup.addTo(map);
});
map.on('mouseleave', 'lakes', () => {
map.getCanvas().style.cursor = '';
popup.remove();
});
map.on('click', 'lakes', (event) => {
const features = map.queryRenderedFeatures(event.point, {
layers: ['lakes']
});
if (event.features.length === 0) return;
window.location.href = ('/lakes/' + features[0].properties.url + '/');
});
document.getElementById("lakes-header").onmouseover = function() {
MyMouseOver();
};
function MyMouseOver() {
document.getElementById("wrapper").style.display = "none";
document.getElementById("lakes-header").style.display = "none";
}
});
The issue stems from the popup box on top of the layer and can be fixed by adding the CSS property 'cursor-events: none' to the popup. That should stop the flickering and shouldn't interfere with the layers.

Open the popups of all markers that are visible on the map with a zoom > 10

I need to open all the markers that are visible on the map at Zoom,
10. I also use leaflet.markercluster.
Init map:
initMap() {
this.map = L.map('map', {
center: [55.55, 37.61],
zoom: 9,
layers: this.layer
})
this.tileLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution:
'© OpenStreetMap, ©'
})
this.tileLayer.addTo(this.map)
this.map.on('zoom', function(ev) {
???
})
Add marker layer:
this.markerLayer = new L.LayerGroup() // layer contain searched elements
// this.map.addLayer(this.markerLayer)
for (const i in data) {
...
const marker = new L.Marker(new L.latLng(loc), { title: title, icon: icon })// se property searched
marker.bindPopup(title)
this.markerLayer.addLayer(marker)
}
Use leaflet marker cluster:
this.markersLayer = L.markerClusterGroup({
iconCreateFunction: function(cluster) { ... },
singleMarkerMode: false
})
this.markersLayer.addLayer(this.markerLayer)
this.map.addLayer(this.markersLayer)
You should add your markers to an array before / after adding them to the map to access them easily.
var markers = [];
for (const i in data) {
const marker = new L.Marker(new L.latLng(loc), { title: title, icon: icon })
marker.bindPopup(title)
this.markerLayer.addLayer(marker)
markers.push(marker);
}
after that you can just loop through your markers array and use openPopUp function of marker to open popups of your markers programmatically.
for(i = 0; i< markers.length;i++){
markers[i].openPopup();
}

react-leaflet search plugin not working. Can anyone help me out with this

I tried to implement react-leaflet search from https://github.com/tumerorkun/react-leaflet-search but, it didn't worked.
following is my code (without including react-leaflet search). Can anyone help me with it.
Hi, I tried to implement react-leaflet search from https://github.com/tumerorkun/react-leaflet-search but, it didn't worked.
following is my code (without including react-leaflet search). Can anyone help me with it.
import React from "react";
import L from "leaflet";
import 'leaflet-timedimension/dist/leaflet.timedimension.src';
import omnivore from '#mapbox/leaflet-omnivore';
import { Map, Marker, Popup } from 'react-leaflet';
import { ReactLeafletSearch } from 'react-leaflet-search';
// import * as countries from './data/map.geojson';
const config = {};
config.default = {
center: [51.505,-0.09],
zoomControl: true,
zoom: 4,
maxZoom: 19,
minZoom: 11,
scrollWheel: false,
legends: true,
infoControl: true,
attributionControl: true
};
config.tdOptions = {
timeInterval: "2018-09-30/2018-10-30",
period: "PT1H",
};
// ===== Example data sources
config.wmsOne = {
url: "https://demo.boundlessgeo.com/geoserver/ows",
options: { layers: 'nasa:bluemarble', transparent: true },
attribution: "&copy <a href="http://osm.org/copyright">CHANGE THIS</a> contributors",
};
config.wmsTwo = {
url: "https://demo.boundlessgeo.com/geoserver/ows",
options: { layers: 'ne:ne', transparent: true },
attribution: "&copy <a href="http://osm.org/copyright">CHANGE THIS</a> contributors",
};
config.osmLayer = {
url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
params: {
minZoom: 11,
attribution: "&copy <a href="http://osm.org/copyright">CHANGE THIS</a> contributors",
id: '',
accessToken: ''
}
};
// ===== END Example data sources
export default class LeafletMap extends React.Component {
constructor() {
super();
this.state = {
lat: config.default.center[0],
lng: config.default.center[1],
zoom: config.default.zoom,
toggleActive: true,
timeInterval: config.tdOptions.timeInterval,
period: config.tdOptions.period,
gpxLayer: null,
gpxTimeLayer: null,
};
this.initMap = this.initMap.bind(this);
this.initTimeDimension = this.initTimeDimension.bind(this);
this.onClick = this.onClick.bind(this); // Necessary?
}
// Executed when component is mounted Leaflet-React MAP component
componentDidMount() {
this.initMap();
// this.initTimeDimension(); // TODO: MAKE WORK GOOD!
}
initMap() {
// Usual Leaflet way, but we're using react-leaflet's <Map> component instead
/*this.map = new L.map("root", {
center: [this.state.lat, this.state.lng],
zoom: config.params.zoom,
timeDimension: true
});*/
console.log("### Initializing Leaflet map");
// Tile layer(s)
const tileLayerA =
L.tileLayer.wms(config.wmsOne.url, config.wmsOne.options);
const tileLayerB =
L.tileLayer.wms(config.wmsTwo.url, config.wmsTwo.options);
const tileLayerC = L.tileLayer.wms(config.osmLayer.url)
.addTo(this.map.leafletElement);
// const countriesLayer = L.geoJson(countries, {});
// Add controls for toggling layers
L.control.layers({
"OSM Layer": tileLayerC,
"Layer Two": tileLayerA,
"Layer One": tileLayerB
}).addTo(this.map.leafletElement);
}
// TODO: Make work!
initTimeDimension() {
console.log("### Init Leaflet TimeDimension");
let gpxTl = L.timeDimension.layer.geoJson(this.state.gpxLayer, {
updateTimeDimension: true,
addlastPoint: true,
waitForReady: true
});
this.setState({gpxLayer: omnivore.gpx('public/running_mallorca.gpx')});
this.setState({gpxTimeLayer: gpxTl});
// TimeDimension layer(s)
const td = new L.timeDimension({
period: "PT5M",
});
this.map.timeDimension = td;
//Player -> Component to animate a map with a TimeDimension, changing the time periodically.
let player = new L.TimeDimension.Player({
transitionTime: 100,
loop: false,
startOver:true
}, td);
L.control.timeDimension({
player: player,
}).addTo(this.map.leafletElement);
// Add timedimension from GPX data
new L.timeDimension.layer.geoJson(this.state.tdData, {
updateTimeDimension: true,
addlastPoint: true,
waitForReady: true
}).addTo(this.map.leafletElement);
}
onClick = () => {
this.setState({
toggleActive: !this.state.toggleActive,
});
console.log('CLICKED MAP');
// this.map.leafletElement.fitBounds(this.state.tdData);
};
render() {
const position = [this.state.lat, this.state.lng];
const timeDimensionOptions = {
timeInterval: this.state.timeInterval,
period: this.state.period
};
return (
<React.StrictMode>
<Map
center={position}
zoom={this.state.zoom}
onClick={this.onClick}
timeDimension={true}
timeDimensionOptions={timeDimensionOptions}
timeDimensionControl={true}
ref={(ref) => { this.map = ref; }}>
{/*<TileLayer
attribution={config.wmsOne.attribution}
url={config.wmsOne.url}
/>*/}
{/*<WMSTileLayer
layers={this.state.toggleActive ? 'nasa:bluemarble' : 'ne:ne'}
url="https://demo.boundlessgeo.com/geoserver/ows" />*/}
<Marker position={position}>
<Popup>
A pretty CSS3 popup (react-leaflet component). <br />Easily customizable.
</Popup>
</Marker>
</Map>
</React.StrictMode>
);
} // END of render()
}
Use this :
import { SearchControl } from 'react-leaflet-search';
It works, although it's not on the Documentation
Can you post a jsfiddle or codepen demonstrating the problem?
Also... incidentally the way you are adding controls and layers to the map is not recommended by react-leaflet.
new L.timeDimension.layer.geoJson(this.state.tdData, {...}).addTo(this.map.leafletElement);
is imperative. Prefer declarative rendering like
import { Map, TileLayer, GeoJSON } from 'react-leaflet';
<Map>
<TileLayer>
<GeoJSON>
</Map>

Ionic DevApp: Google maps not showing

I have used JavaScript SDK to display map.
It's working on the browser but when I open it on dev app, the page shows the blank page.
ionViewDidLoad(){
this.loadMap();
}
loadMap(){
this.geolocation.getCurrentPosition().then((position) => {
let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}, (err) => {
console.log(err);
});
}
Try to add locationOption
let locationOptions = { timeout: 30000, enableHighAccuracy: true };
and pass to getCurrentPosition like this
this.geolocation.getCurrentPosition(locationOptions).then((p‌​osition) => {

Add an info window to each marker when select place in list view

// inital Locations
var myLocations = [{
name: "Istanbul",
address: "214 S Highland Ave, Pittsburgh, PA",
latlng: {
lat: 41.008238,
lng: 28.978359
}
}, {
name: "Antalya",
address: "5469 Penn Ave Pittsburgh, PA 15206",
latlng: {
lat: 36.896891,
lng: 30.713323
}
}, {
name: "Ankara",
address: "236 Fifth Ave Pittsburgh, PA 15222",
latlng: {
lat: 39.933363,
lng: 32.859742
}
}, {
name: "Trabzon",
address: "5608 Walnut St Pittsburgh, PA 15232",
latlng: {
lat: 41.002697,
lng: 39.716763
}
}, {
name: "Bursa",
address: "5841 Penn Ave Pittsburgh, PA 15206",
latlng: {
lat: 40.188528,
lng:29.060964
}
},
];
//String to display in info window
//Declare Map variable and markers array
var map;
var infoWindow;
var marker;
//Create Instance of a map from the Google maps api
//Grab the reference to the "map" id to display map
//Set the map options object properties
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 38.963745,
lng: 35.243322
},
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
};
// tells the view model what to do when a change occurs
function mLocation(value) {
this.name = ko.observable(value.name);
this.address = ko.observable(value.address);
this.description = ko.observable(value.description);
this.latlng = ko.observable(value.lat);
};
//ViewModel
function ViewModel() {
var self = this;
self.markers = [];
//Copies the values of initialLocations and stores them in sortedLocations(); observableArray
self.sortedLocations = ko.observableArray(myLocations);
//Adds new markers at each location in the initialLocations Array
self.sortedLocations().forEach(function(location) {
marker = new google.maps.Marker({
position: location.latlng,
map: map,
title: location.name,
icon: 'img/marker.png',
animation: google.maps.Animation.DROP
});
location.marker = marker;
var content = '<div id="iw_container">' +
'<div class="iw_title">' + name + </div>';
//Pushes each marker into the markers array
this.markers.push(marker);
});
//Map info windows to each item in the markers array
self.markers.map(function(info) {
infoWindow = new google.maps.InfoWindow({
content: content
});
//Add click event to each marker to open info window
info.addListener('click', function() {
infoWindow.open(map, this),
info.setAnimation(google.maps.Animation.BOUNCE) //Markers will bounce when clicked
setTimeout(function() {
info.setAnimation(null)
}, 2000); //Change value to null after 2 seconds and stop markers from bouncing
});
});
//Click on item in list view
self.listViewClick = function(loc) {
if (loc.name) {
map.setZoom(15); //Zoom map view
map.panTo(loc.latlng); // Pan to correct marker when list view item is clicked
loc.marker.setAnimation(google.maps.Animation.BOUNCE); // Bounce marker when list view item is clicked
infoWindow.open(map, loc.marker); // Open info window on correct marker when list item is clicked
}
setTimeout(function() {
loc.marker.setAnimation(null); // End animation on marker after 2 seconds
}, 2000);
};
// Stores user input
self.query = ko.observable('');
//Filter through observableArray and filter results using knockouts utils.arrayFilter();
self.search = ko.computed(function() {
return ko.utils.arrayFilter(self.sortedLocations(), function(listResult) {
return listResult.name.toLowerCase().indexOf(self.query().toLowerCase()) >= 0;
});
});
};
$(document).ready(function() {
initMap();
ko.applyBindings(ViewModel());
});
I would like to ask about how to add an info window to a marker in Google Maps. The condition is, I have to create a program with multiple markers on a map. But how I can give a specified info window to each marker when select in each place in the view list?