javascript – 如何在OpenLayers中向向量添加弹出框?

前端之家收集整理的这篇文章主要介绍了javascript – 如何在OpenLayers中向向量添加弹出框?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的程序的先前版本中,我使用标记标记地图上的点.在当前版本中,我不得不从标记更改为向量,因为我需要额外的灵活性.在标记解决方案中,我使用下面的函数标记添加一个弹出框:
  1. function createPopupBoxFeature(vector,lonLat,description) {
  2. var feature = new OpenLayers.Feature(vector,lonLat);
  3.  
  4. feature.closeBox = true;
  5. feature.popupClass = OpenLayers.Class(OpenLayers.Popup.AnchoredBubble,{ "autoSize": true });
  6. feature.data.popupContentHTML = description;
  7.  
  8. vector.events.register("mousedown",feature,function(evt) {
  9. if (this.popup == null) {
  10. this.popup = this.createPopup(this.closeBox);
  11. map.addPopup(this.popup);
  12. this.popup.show();
  13. } else {
  14. this.popup.toggle();
  15. }
  16. OpenLayers.Event.stop(evt);
  17. });
  18.  
  19. return feature;
  20. }

但它不再适用于矢量,因为它们没有事件属性.我该如何解决

解决方法

实际上,官方的做法如下:

(注意:某些变量尚未在这些片段中声明:longt,lat,map)

http://dev.openlayers.org/examples/light-basic.html

  1. //Step 1 - create the vector layer
  2. var vectorLayer = new OpenLayers.Layer.Vector("ExampleLayer",{
  3. eventListeners:{
  4. 'featureselected':function(evt){
  5. var feature = evt.feature;
  6. var popup = new OpenLayers.Popup.FramedCloud("popup",OpenLayers.LonLat.fromString(feature.geometry.toShortString()),null,feature.attributes.message+"<br>"+feature.attributes.location,true,null
  7. );
  8. popup.autoSize = true;
  9. popup.maxSize = new OpenLayers.Size(400,800);
  10. popup.fixedRelativePosition = true;
  11. feature.popup = popup;
  12. map.addPopup(popup);
  13. },'featureunselected':function(evt){
  14. var feature = evt.feature;
  15. map.removePopup(feature.popup);
  16. feature.popup.destroy();
  17. feature.popup = null;
  18. }
  19. }
  20. });
  21.  
  22. //Step 2 - add feature to layer
  23. var p = new OpenLayers.Geometry.Point(longt,lat);
  24. var feature = new OpenLayers.Feature.Vector(
  25. p.transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()),{message:'foo',location:'bar'},{externalGraphic: '../img/marker.png',graphicHeight: 21,graphicWidth: 16}
  26. );
  27. vectorLayer.addFeatures(feature);
  28.  
  29. //Step 3 - create the selectFeature control
  30. var selector = new OpenLayers.Control.SelectFeature(vectorLayer,{
  31. hover:true,autoActivate:true
  32. });
  33.  
  34. //Step 4 - add the layer and control to the map
  35. map.addControl(selector);
  36. map.addLayer(vectorLayer);

猜你在找的JavaScript相关文章