javascript - 使用 JavaScript 打开/关闭传单标记弹出窗口
问题描述
我有以下代码,它创建一个新标记,Drag me!
每次单击时都会显示。
pin = L.marker([map.getCenter().lat, map.getCenter().lng], {icon:greenIcon, draggable:true, autoPan:true}).addTo(map);
pin.bindPopup('Drag me!');
我可以使用 JavaScript 打开弹出窗口吗?我该怎么做?最初我希望它在创建时自动打开,但我可以看到自己也需要在其他情况下打开它。
解决方案
使用原生传单的openPopup()
方法。资源
当你创建你的标记时,你所要做的就是像这样调用这个方法:
pin.openPopup();
每次您想以编程方式打开标记时都执行此操作。
<!DOCTYPE html>
<html>
<head>
<title>Quick Start - Leaflet</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin=""></script>
</head>
<body>
<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>
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 © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(map);
var greenIcon = L.icon({
iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
shadowUrl: 'https://leafletjs.com/examples/custom-icons/leaf-shadow.png',
iconSize: [38, 95], // size of the icon
shadowSize: [50, 64], // size of the shadow
iconAnchor: [22, 94], // point of the icon which will correspond to marker's location
shadowAnchor: [4, 62], // the same for the shadow
popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
});
const pin = L.marker([map.getCenter().lat, map.getCenter().lng], {
icon: greenIcon,
draggable: true,
autoPan: true
}).addTo(map);
pin.bindPopup('Drag me!');
pin.openPopup();
</script>
</body>
</html>
推荐阅读
- excel - 引用公式的值(字符串)并检查单元格(句子)是否包含该值
- javascript - 下拉列表
- composition - 实践中的作文
- java - CompletableFuture thenCompletable after 异常
- php - 为什么 libxml_use_internal_errors(true) 不尊重 LIBXML_NOWARNING?
- c - 如何优化多个strncmp以下?
- mysql - 劳动力管理数据库设计
- c# - 值不能为空。参数名称:messageId
- javascript - Mailgun API 路由:电子邮件被多次发送
- vue.js - Vue.js:当用户单击按钮时加载模板(或 div)?