How to display the latitude and longitude in from this code using Openlayers?

前端 未结 1 1307
野趣味
野趣味 2021-01-07 14:55

    
    

        
相关标签:
1条回答
  • 2021-01-07 15:36

    This is what you need:

    map.events.register("click", map, function(e) {
      var position = map.getLonLatFromPixel(e.xy);
    
      OpenLayers.Util.getElement("mydiv").innerHTML = 
            position.lon.toFixed(3) + ', ' + position.lat.toFixed(3);
    
    });
    

    You can see here the code working: http://jsbin.com/uyuka6

    So, your code should looks:

    function init(){
    
          var map, vectors, controls;
          map = new OpenLayers.Map('map');
          var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS",
            "http://vmap0.tiles.osgeo.org/wms/vmap0?", {layers: 'basic'});
    
          vectors = new OpenLayers.Layer.Vector("Vector Layer");
    
          map.addLayers([wms, vectors]);
          map.addControl(new OpenLayers.Control.LayerSwitcher());
          map.addControl(new OpenLayers.Control.MousePosition());
          //map.addControl(new OpenLayers.Control.Click());
    
          map.events.register("click", map, function(e) {
             var position = map.getLonLatFromPixel(e.xy);
    
             OpenLayers.Util.getElement("shortdesc").innerHTML =
                 position.lon.toFixed(3) + ', ' + position.lat.toFixed(3);
    
          });
    
          controls = {
               point: new OpenLayers.Control.DrawFeature(vectors,
                 OpenLayers.Handler.Point),
    
               line: new OpenLayers.Control.DrawFeature(vectors,
                 OpenLayers.Handler.Path),
               polygon: new OpenLayers.Control.DrawFeature(vectors,
                 OpenLayers.Handler.Polygon),
               drag: new OpenLayers.Control.DragFeature(vectors)
           };
    
           var poly = controls['polygon'].handler;
           poly.callbacks.point = function(point){
               OpenLayers.Util.getElement("docs").innerHTML = point.toString();
           };
    
           var line = controls['line'].handler;
           line.callbacks.point = function(point){
              OpenLayers.Util.getElement("docs").innerHTML = point.toString();
           };
    
           for(var key in controls) {
              map.addControl(controls[key]);
              // map.addControl(click);
           }
    
           map.setCenter(new OpenLayers.LonLat(0, 0), 3);
           document.getElementById('noneToggle').checked = true;
    }
    
    0 讨论(0)
提交回复
热议问题