首页 > 解决方案 > 多边形未绘制 // 表示变量不存在,但控制台中没有返回错误

问题描述

我正在尝试在地图上显示多边形,我在此地图上使用的数据来自带有数组的数据库,当我得到这些坐标console.log时,我尝试使用的完整坐标是这些[obj[2][0].geometry.coordinates[0][0][0]4.87896

0: (2) ["4.87896", "52.367477"]
1: (2) ["4.87896", "52.379843"]
2: (2) ["4.918785", "52.379843"]
3: (2) ["4.918785", "52.367477"]
4: (2) ["4.87896", "52.367477"] 

以及我如何尝试使多边形显示在地图上的代码

let map = L.map('map').setView([52.37, 4.90], 13);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: 'Map data &copy; <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>',
    maxZoom: 14,

}).addTo(map);
var polygon = L.polygon([
        [obj[2][0].geometry.coordinates[0][0][0], obj[2][0].geometry.coordinates[0][0][1]],
        [obj[2][0].geometry.coordinates[0][1][0], obj[2][0].geometry.coordinates[0][1][1]],
        [obj[2][0].geometry.coordinates[0][2][0], obj[2][0].geometry.coordinates[0][2][1]],
        [obj[2][0].geometry.coordinates[0][3][0], obj[2][0].geometry.coordinates[0][3][1]],
        [obj[2][0].geometry.coordinates[0][4][0], obj[2][0].geometry.coordinates[0][4][1]]
    ]).addTo(map); 

多边形没有显示在地图上,但是console当我输入它polygon时也没有返回错误。console

VM94:1 未捕获的 ReferenceError:多边形未定义于:1:1

我使用的所有链接

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css"
      integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
      crossorigin=""/>
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"
        integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
        crossorigin=""></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.js"></script>

编辑:js的一个bin

https://output.jsbin.com/lewaroc/1

标签: javascriptleaflet

解决方案


经过一些测试,我发现坐标只接受numbers,所以在这种情况下它必须是Number([obj[2][0].geometry.coordinates[0][0][0]),然后画得很好


推荐阅读