我的目標是在OpenLayers 3中爲我的工作創建一個包含多個圖層的地圖。一個從OpenStreetMaps獲取基本的源。另一個將是一個透明圖層,顯示區域輪廓(尚未完成)。第三個是我遇到的問題,它顯示了一系列代表地圖上感興趣的個人站點的圖標。我從包含在一個單獨的腳本文件中的JS數據結構中加載這些站點。我設法讓我的代碼添加出現在正確緯度/經度上的功能。我的下一步是在點擊圖標時顯示HTML框(div),以顯示該地圖的前面(以顯示該網站的詳細信息)。但是,我無法得到這個工作。對於我的noobish編碼抱歉,但它真的讓我難住,我非常感謝任何幫助。OL3 - 故障檢測功能點擊
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="ol.css" type="text/css">
<link rel="stylesheet" href="map.css" type="text/css">
<script src="ol.js" type="text/javascript"></script>
<script src="sites.js" type="text/javascript"></script>
<script type="text/javascript">
function buildLayerFromSites(allSites)
// allSites is just an array of data structures
{
var count, site;
// for each site in the array, make a feature
for (count=0;count<allSites.length;count++)
{
geom = new ol.geom.Point(ol.proj.fromLonLat([allSites[count].longitude,allSites[count].latitude]));
site = new ol.Feature(geom);
site.Name = allSites[count].siteName; // <-- can I assign further details in the structure like this?
var siteStyle = new ol.style.Style({
image: new ol.style.Icon ({
src: 'icon-blue.png',
scale: 0.1,
opacity: 0.9,
})
})
site.setStyle(siteStyle);
siteFeatures[count] = site;
}
siteSource = new ol.source.Vector ({
features: siteFeatures
})
siteLayer = new ol.layer.Vector({
source: siteSource
});
map.addLayer(siteLayer);
}
</script>
<title>Map</title>
</head><body>
...
<div id="map" class="map">
...
<script type="text/javascript">
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([115.51, -31.57]),
zoom: 8
})
});
buildLayerFromSites(includeSites); // adds the second layer with the sites
// click event handler, basically same as http://openlayers.org/en/v3.12.1/examples/icon.html
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature,layer) {
return feature;
});
if (feature) {
console.log("feature got clicked on"); // do stuff
} else {
console.log("didn't click a feature");
}
});
</script>
</body>
</html>
地圖和圖標的負載,但是當我點擊的圖標,無論怎麼放大或縮小我,它沒有檢查出我點擊圖標匹配。事情是,事件處理程序代碼與官方示例中的相同,這使我認爲這是我創建功能的方式。另一方面,這些功能可以很好地顯示爲圖標,只是點擊事件看起來不起作用。從示例中更改鼠標光標會發生類似的奇怪事情。我猜這是因爲我不明白數據/功能在OL中的結構方式,我發現文檔沒有完全解釋它是如何工作的,所以我一直在寫這樣的代碼片段試圖看看:
var myLayers = map.getLayers();
console.log("keys - " + myLayers.getKeys); // prints out 'function(){return Object.keys(this.B)}' - what does that mean?
var mySource = myLayers.getSource;
console.log("source" + mySource.getProjection); // doesn't work
var features = mySource.getFeatures; // says mySource is undefined
當然,它完全失敗。
如何獲取它以檢測圖標/功能上的點擊,以便我可以告訴div出現並在正確的時間顯示我的數據?我做對了嗎?我對數據/函數的工作方式有什麼不瞭解?我是一個很大的JS noob,所以我希望我不會做一些愚蠢的事情,但這會造成我很大的問題,我真的可以用你的幫助!謝謝大家!
感謝您的耐心解答。大規模的菜鳥錯誤!那麼,我如何打印它返回的內容呢?先把它放在一個變量中?或者因爲它不是簡單的數據類型,我不能? – HealthyCode
您可以使用console.log將其打印到控制檯,只需先嚐試一下,隊友 –
OIC是的,現在我明白了。再次感謝耐心。它現在說myLayers.getSource不是一個函數,即使這個函數在文檔中,但至少我更接近一個更少的noob錯誤! – HealthyCode