为什么我使用 OpenLayers 在两个弹出窗口中得到相同的文本 [英] Why do i get same text in both Pop-ups using OpenLayers

查看:65
本文介绍了为什么我使用 OpenLayers 在两个弹出窗口中得到相同的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 OpenLLayers 5.我在数据库的数组中保存了经度、纬度和汽车名称.我可以显示两个标记(我的数组目前只有两个索引).每个标记都有一个弹出窗口,其中应包含其名称、经度、纬度.例如,第一个 Marker's Pop-up 将 car 1 作为文本.在我的例子中,汽车名称是 vehName.我总是在两个弹出窗口上显示第二辆车的信息(这是我数组的最后一个索引).任何人都可以帮我找到解决方案吗?

/* 打开街道地图最新版本 */var map = new ol.Map({target: 'map',//div id层数:[新的 ol.layer.Tile({来源:新 ol.source.OSM()})],视图:新 ol.View({中心:ol.proj.fromLonLat([4.35247, 52.520008]),变焦:6,最小缩放:3})});for(var i=0; i 

代码片段:

/* 打开街道地图最新版本 */var map = new ol.Map({target: 'map',//div id层数:[新的 ol.layer.Tile({来源:新 ol.source.OSM()})],视图:新 ol.View({中心:ol.proj.fromLonLat([4.35247, 52.520008]),变焦:6,最小缩放:3})});var arrayPos = [[1.297355, 52.6308859, 0, "80"],[0.121817, 52.205337, 0, "85"]];var vectorSource = new ol.source.Vector();//来源();for (var i = 0; i < arrayPos.length; i++) {//信息var long = arrayPos[i][0]var lat = arrayPos[i][1];var vehName = arrayPos[i][2];var BatteryCharge = arrayPos[i][3];//创建一个特征var 特征 = 新 ol.Feature({几何:新 ol.geom.Point(ol.proj.fromLonLat([long, lat]))})feature.set('batteryCharge', batteryCharge);vectorSource.addFeature(feature);}//在地图上添加一个标记var layer = new ol.layer.Vector({来源:vectorSource});layer.setStyle(new ol.style.Style({图像:新 ol.style.Icon({src: 'https://wiki.openstreetmap.org/w/images/0/0c/Hgv.png',//scale: 0.4//设置地图上车辆的大小})}));地图.addLayer(层);//初始化弹出窗口var container = document.getElementById('popup');var content = document.getElementById('popup-content');var 覆盖 = 新 ol.Overlay({元素:容器,自动平移:真,自动平移动画:{持续时间:250}});map.addOverlay(overlay);//使用鼠标悬停事件显示弹出窗口map.on('pointermove', function(event) {const features = map.getFeaturesAtPixel(event.pixel);if (features.length > 0) {var 坐标 = event.coordinate;const BatteryCharge = features[0].get('batteryCharge');//在弹出窗口中写入的简单文本,值只是第二个索引content.innerHTML = event.traget + '<br><b>电池状态:</b>'+ 电池充电;overlay.setPosition(坐标);} 别的 {覆盖.setPosition(未定义);}});

html,身体,.地图 {高度:100%;宽度:100%;填充:0px;边距:0px;}/* 地图弹出窗口 */.ol-弹出{位置:绝对;背景颜色:白色;box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);填充:15px;边框半径:10px;边框:1px 实心 #cccccc;底部:12px;左:-50px;最小宽度:280px;}.ol-popup:之后,.ol-popup:before {顶部:100%;边框:实心透明;内容: " ";高度:0;宽度:0;位置:绝对;指针事件:无;}.ol 弹出:{边框顶部颜色:白色;边框宽度:10px;左:48px;左边距:-10px;}.ol-popup:before {边框顶部颜色:#cccccc;边框宽度:11px;左:48px;左边距:-11px;}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/css/ol.css" type="text/css"><script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script><title>OpenLayers 示例</title><div id="map" class="map"></div><div id="popup" class="ol-popup"><div id="popup-content"></div>

I am using OpenLLayers 5. I saved Longitude, Latitude and car name in an array from the Database. I could display two Markers(My Array has just two indexes for the moment). Each Marker has a Pop-up window which should contain its name, longitude, latitude. For Example first Marker's Pop-up has car 1 as a text. The car name is vehName in my case. I am always getting the Informations of the second car(which is the last index of my Array) displayed on both Pop-ups. Could anyone please help me find out a solution for this?

/* open street map newest version */
var map = new ol.Map({
    target: 'map', // the div id
    layers: [
        new ol.layer.Tile({
        source: new ol.source.OSM()
        })
    ],
    view: new ol.View({ 
        center: ol.proj.fromLonLat([4.35247, 52.520008]),
        zoom: 6,
        minZoom: 3
    })
});
for(var i=0; i < arrayPos.length; i++) {
    var long = arrayPos[i][0]
    var lat = arrayPos[i][1];
    var vehName = arrayPos[i][2];
    var batterCharge = arrayPos[i][3];
    console.log(batterCharge);
    // add a marker to the map
    var layer = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: [
                new ol.Feature({
                    geometry: new ol.geom.Point(ol.proj.fromLonLat([long, lat]))
                })  
            ]
        })
    });
    layer.setStyle(new ol.style.Style({
        image: new ol.style.Icon({
        src: 'https://wiki.openstreetmap.org/w/images/0/0c/Hgv.png', //
        scale: 0.4 // set the size of the vehicle on the map
        })
    }));
    map.addLayer(layer);
    //initialize the popup
    var container = document.getElementById('popup');
    var content = document.getElementById('popup-content');

    var overlay = new ol.Overlay({
        element: container,
        autoPan: true,
        autoPanAnimation: {
            duration: 250
        }
    });
    map.addOverlay(overlay);

    //display the pop with on mouse over event
    map.on('pointermove', function (event) {
        if (map.hasFeatureAtPixel(event.pixel) === true) {  
            var coordinate = event.coordinate;
            //simple text written in the popup, values are just of the second index
            content.innerHTML = vehName+'<br><b>Batteriestatus: </b>'+batterCharge;//just the second one is getting displayed
            overlay.setPosition(coordinate);
        }
        else {
            overlay.setPosition(undefined);
        }
    });
}

Edited version! Still not working though! any ideas?

for(var i=0; i < arrayPos.length; i++) {
    //infos
    var long = arrayPos[i][0]
    var lat = arrayPos[i][1];
    var vehName = arrayPos[i][2];
    var batteryCharge = arrayPos[i][3];
    
    //create a feature
    var feature = new new ol.Feature({
        geometry: new ol.geom.Point(ol.proj.fromLonLat([long, lat]))
    })
    feature.set('batteryCharge', batteryCharge);
    vectorSource.add(feature);
}   
// add a marker to the map
var vectorSource = new ol.source.VectorSource();
var layer = new ol.layer.Vector({
    source: vectorSource({
        features: [feature]
    })
});

layer.setStyle(new ol.style.Style({
    image: new ol.style.Icon({
    src: 'https://wiki.openstreetmap.org/w/images/0/0c/Hgv.png', //
    scale: 0.4 // set the size of the vehicle on the map
    })
}));
map.addLayer(layer);

//initialize the popup
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');

var overlay = new ol.Overlay({
    element: container,
    autoPan: true,
    autoPanAnimation: {
        duration: 250
    }
});
map.addOverlay(overlay);

//display the pop with on mouse over event
map.on('pointermove', function (event) {
    if (map.hasFeatureAtPixel(event.pixel) === true) {  
        var coordinate = event.coordinate;
        const features = event.target.getFeatures();
        const batteryCharge  = features.get(0).get('batteryCharge');

        //simple text written in the popup, values are just of the second index
        content.innerHTML = event.traget+'<br><b>Batteriestatus: </b>'+batteryCharge;
        overlay.setPosition(coordinate);
    }
    else {
        overlay.setPosition(undefined);
    }
});

解决方案

You have many syntax errors in the posted code.

  1. The first error I get with your code is Uncaught ReferenceError: arrayPos is not defined (because it isn't).

  2. When I add that array, I get a syntax error: Uncaught TypeError: (intermediate value) is not a constructor on this line:

    var feature = new new ol.Feature({
    

    (extra new)

  3. When I remove the extra new, I get a syntax error: Uncaught TypeError: Cannot read property 'add' of undefined on this line:

    vectorSource.add(feature);
    

    because vectorSource is not yet defined.

  4. When I move the definition up above that line, I get a syntax error: Uncaught TypeError: ol.source.VectorSource is not a constructor (because with ol.js that should be ol.source.Vector).

  5. When I fix that, I get a syntax error: Uncaught TypeError: vectorSource.add is not a function (because it isn't a function, that should be addFeature).

  6. When I fix that, I get a syntax error: Uncaught TypeError: vectorSource is not a function on these lines:

    source: vectorSource({
       features: [feature]
    })
    

    (because it isn't, that should be the variable vectorSource that you added the markers to)

Now I get markers on the map, but still get a syntax error: Uncaught TypeError: event.target.getFeatures is not a function

You aren't using @Mike's code from your other question: Display Multiple Markers on OpenLayers 5 dynamically with Pop-up window:

const features = map.getFeaturesAtPixel(event.pixel);
if (features.length > 0) {
    var coordinate = event.coordinate;
    const batteryCharge = features[0].get('batteryCharge');

If I use that, I get popups (with different values) for each marker.

(and "undefined" in the text because: event.traget isn't defined.

proof of concept fiddle

code snippet:

/* open street map newest version */
var map = new ol.Map({
  target: 'map', // the div id
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([4.35247, 52.520008]),
    zoom: 6,
    minZoom: 3
  })
});
var arrayPos = [
  [1.297355, 52.6308859, 0, "80"],
  [0.121817, 52.205337, 0, "85"]
];
var vectorSource = new ol.source.Vector(); // Source();
for (var i = 0; i < arrayPos.length; i++) {
  //infos
  var long = arrayPos[i][0]
  var lat = arrayPos[i][1];
  var vehName = arrayPos[i][2];
  var batteryCharge = arrayPos[i][3];

  //create a feature
  var feature = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([long, lat]))
  })
  feature.set('batteryCharge', batteryCharge);
  vectorSource.addFeature(feature);
}
// add a marker to the map

var layer = new ol.layer.Vector({
  source: vectorSource
});

layer.setStyle(new ol.style.Style({
  image: new ol.style.Icon({
    src: 'https://wiki.openstreetmap.org/w/images/0/0c/Hgv.png', //
    scale: 0.4 // set the size of the vehicle on the map
  })
}));
map.addLayer(layer);

//initialize the popup
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');

var overlay = new ol.Overlay({
  element: container,
  autoPan: true,
  autoPanAnimation: {
    duration: 250
  }
});
map.addOverlay(overlay);

//display the pop with on mouse over event
map.on('pointermove', function(event) {
  const features = map.getFeaturesAtPixel(event.pixel);
  if (features.length > 0) {
    var coordinate = event.coordinate;
    const batteryCharge = features[0].get('batteryCharge');

    //simple text written in the popup, values are just of the second index
    content.innerHTML = event.traget + '<br><b>Batteriestatus: </b>' + batteryCharge;
    overlay.setPosition(coordinate);
  } else {
    overlay.setPosition(undefined);
  }
});

html,
body,
.map {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}


/* Map popup */

.ol-popup {
  position: absolute;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 280px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/css/ol.css" type="text/css">
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script>
<title>OpenLayers example</title>
<div id="map" class="map"></div>
<div id="popup" class="ol-popup">
  <div id="popup-content"></div>
</div>

这篇关于为什么我使用 OpenLayers 在两个弹出窗口中得到相同的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆