OpenLayer映射未捕获的类型错误无法读取属性addlayer

时间:2019-03-02 18:38:13

标签: javascript openlayers

我一直在使用以下示例代码:https://mediarealm.com.au/articles/openstreetmap-openlayers-map-markers/

它说我应该可以在体内的任何位置调用add_map_point,但是当我这样做时会出现错误:

未捕获的TypeError:无法读取未定义的属性'addLayer'     在add_map_point

我认为这是因为我在完全初始化地图之前以某种方式调用了它,但是我不知道解决方案是什么。

我尝试将<script>标签和JavaScript移入正文,但是这导致地图完全无法加载。如果我从

调用函数
<body onload="initialize_map(); add_map_point(-33.8688, 151.2093);"> 

然后它将按我期望的方式添加一个标记,但是从其他任何地方调用该函数(使用<script>标记或根据需要从php内部调用)都会给我带来该错误。

这是我的代码:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Interface-PageStyle.css" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v4.6.5/build/ol.js" type="text/javascript"></script>

<script>
/* OSM & OL example code provided by https://mediarealm.com.au/ */
var map;
var mapLat = 52.626603;
var mapLng = -1.330148;
var mapDefaultZoom = 10;

function initialize_map() {
map = new ol.Map({
target: "map",
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
url: "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([mapLng, mapLat]),
zoom: mapDefaultZoom
})
});
}

function add_map_point(lat, lng) {
var vectorLayer = new ol.layer.Vector({
source:new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')),
})]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: "fraction",
anchorYUnits: "fraction",
src: "iconfinder_map-marker_299087.svg"
//Marker icon located at: https://www.iconfinder.com/icons/299087/map_marker_icon, with license: https://creativecommons.org/licenses/by/3.0/, no changes made.
})
})
});

map.addLayer(vectorLayer); //This line is the problem
}
</script>
</head>

<body onload="initialize_map();">

<div id="map" class="mapdiv"></div>
<?php include 'accdatab.php'; 
$volID = $_SESSION['id'];
$sql = "SELECT Latitude, Longitude FROM jobs";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()){
        $lat = $row['Latitude'];
        $lon = $row['Longitude'];
        //echo "<script> add_map_point(0, 0); </script>";
    }
}

?> 
<script> add_map_point(0, 0); </script>

</body>
</html>

0 个答案:

没有答案