leaflet学习(三)----交互事件,弹出点的坐标

2020-01-01  本文已影响0人  悦者生存
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<!--引入css-->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
      integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
      crossorigin=""/>
<style>
    html,body{
        padding:0;
        margin:0;
    }
    #mapid { height: 100vh; }
</style>
<body>
<div id="mapid"></div>
</body>
<!--引入js-->
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
        integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
        crossorigin=""></script>
<script>
    // setView 设定视图  设定地图(设定其地理中心和缩放)
    var mymap = L.map('mapid').setView([51.505, -0.09], 13);
    // L.TileLayer():通过给定URL模板和具有选项的对象来实例化一个切片图层
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        //用来进行属性控制的字符串,描述了图层数据  就是右下角显示的字符串
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(mymap);
    // 创立marker
    var marker = L.marker([51.5, -0.09]).addTo(mymap);
    // 创立circle
    var circle = L.circle([51.508, -0.11], {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5,
        radius: 500
    }).addTo(mymap);
    // 创建 polygon
    var polygon = L.polygon([
        [51.509, -0.08],
        [51.503, -0.06],
        [51.51, -0.047]
    ]).addTo(mymap);
    // 加载弹出窗口
    marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
    // 交互事件,弹出点的坐标
    // function onMapClick(e) {
    //     alert("You clicked the map at " + e.latlng);
    // }
    //
    // mymap.on('click', onMapClick);

    // 以及气泡的方式弹出坐标
    var popup = L.popup();

    function onMapClick(e) {
        popup
            .setLatLng(e.latlng)
            .setContent("You clicked the map at " + e.latlng.toString())
            .openOn(mymap);
    }

    mymap.on('click', onMapClick);
</script>
</html>


上一篇下一篇

猜你喜欢

热点阅读