简体   繁体   English

如何在 MapCenterCoord leaflet 插件中获取坐标?

[英]How to get coordinates in MapCenterCoord leaflet plugin?

I am currently using MapCenterCoord plugin for my leaflet project https://github.com/xguaita/Leaflet.MapCenterCoord我目前正在为我的 leaflet 项目https 使用 MapCenterCoord 插件://github.com/xguaita/Leaflet.MapCenterCoord

The plugin works fine but I am trying to extract the coordinates it produced as a value (and to show it on console.log() so I can reuse it for placing a marker on the map).该插件工作正常,但我试图将它产生的坐标提取为一个值(并将其显示在 console.log() 上,以便我可以重用它在地图上放置标记)。

However, I cannot for the life of me figure out how to get the value out of the plugin.但是,我终其一生都无法弄清楚如何从插件中获取价值。 Anyone got any tips?有人有任何提示吗?

This is the script (I have tried placing console.log in onAdd as console.log(this._getMapCenterCoord()) but to no effect, as it only gives the current GPS onload rather than updated on the console whenever I move the window):这是脚本(我尝试将 console.log 作为console.log(this._getMapCenterCoord())放置在onAdd中,但没有效果,因为它只提供当前的 GPS onload 而不是在我移动窗口时在控制台上更新) :

L.Control.MapCenterCoord = L.Control.extend({
  // Defaults
  options: {
    position: 'bottomleft',
    icon: true,
    onMove: false,
    template: '{y} | {x}', // https://en.wikipedia.org/wiki/ISO_6709
    projected: false,
    formatProjected: '#.##0,000',
    latlngFormat: 'DD', // DD, DM, DMS
    latlngDesignators: false,
    latLngFormatter: undefined
  },

  onAdd: function (map) {
    if (this.options.icon) {
      // create a DOM element and put it into overlayPane
      this._iconEl = L.DomUtil.create('div', 'leaflet-control-mapcentercoord-icon leaflet-zoom-hide');
      map.getPanes().overlayPane.appendChild(this._iconEl);

      // add a viewreset event listener for updating icon's position
      map.on('viewreset', this._onReset, this);
      this._onReset();
    }

    // Control container
    this._container = L.DomUtil.create('div', 'leaflet-control-mapcentercoord');
    L.DomEvent.disableClickPropagation(this._container);

    // Add events listeners for updating coordinates & icon's position
    map.on('move', this._onMapMove, this);
    map.on('moveend', this._onMapMoveEnd, this);

    this._container.innerHTML = this._getMapCenterCoord();
    return this._container;
  },

  onRemove: function (map) {
    // remove icon's DOM elements and listeners
    if (this.options.icon) {
      map.getPanes().overlayPane.removeChild(this._iconEl);
      map.off('viewreset', this._onReset, this);
    }
    map.off('move', this._onMapMove, this);
    map.off('moveend', this._onMapMove, this);
  },

  _onReset: function (e) {
    // update icon's position
    var pos = this._map.latLngToLayerPoint(this._map.getCenter());
    L.DomUtil.setPosition(this._iconEl, pos);
  },

  _onMapMove: function (e) {
    if (this.options.icon) {
      // update icon's position
      var pos = this._map.latLngToLayerPoint(this._map.getCenter());
      L.DomUtil.setPosition(this._iconEl, pos);
    }
    if (this.options.onMove) {
      // update coordinates
      this._container.innerHTML = this._getMapCenterCoord();
    }
  },

  _onMapMoveEnd: function (e) {
    if (this.options.icon) {
      // update icon's position
      var pos = this._map.latLngToLayerPoint(this._map.getCenter());
      L.DomUtil.setPosition(this._iconEl, pos);
    }
    // update coordinates
    this._container.innerHTML = this._getMapCenterCoord();
  },

  _getMapCenterCoord: function () {
    if (this.options.projected) return this._getProjectedCoord(this._map.options.crs.project(this._map.getCenter()));
    return this._getLatLngCoord(this._map.getCenter());
  },

  _getProjectedCoord: function (center) {
    return L.Util.template(this.options.template, {
      x: this._format(this.options.formatProjected, center.x),
      y: this._format(this.options.formatProjected, center.y)
    });
  },


  _getLatLngCoord: function (center) {

    if (this.options.latLngFormatter != undefined) return this.options.latLngFormatter(center.lat, center.lng);

    var lat, lng, deg, min;

    //make a copy of center so we aren't affecting leaflet's internal state
    var centerCopy = {
        lat: center.lat,
        lng: center.lng
    };

    // 180 degrees & negative
    if (centerCopy.lng < 0) {
      centerCopy.lng_neg = true;
      centerCopy.lng = Math.abs(centerCopy.lng);
    } else centerCopy.lng_neg = false;
    if (centerCopy.lat < 0) {
      centerCopy.lat_neg = true;
      centerCopy.lat = Math.abs(centerCopy.lat);
    } else centerCopy.lat_neg = false;
    if (centerCopy.lng > 180) {
      centerCopy.lng = 360 - centerCopy.lng;
      centerCopy.lng_neg = !centerCopy.lng_neg;
    }

    // format
    if (this.options.latlngFormat === 'DM') {
      deg = parseInt(centerCopy.lng);
      lng = deg + 'º ' + this._format('00.000', (centerCopy.lng - deg) * 60) + "'";
      deg = parseInt(centerCopy.lat);
      lat = deg + 'º ' + this._format('00.000', (centerCopy.lat - deg) * 60) + "'";
    } else if (this.options.latlngFormat === 'DMS') {
      deg = parseInt(centerCopy.lng);
      min = (centerCopy.lng - deg) * 60;
      lng = deg + 'º ' + this._format('00', parseInt(min)) + "' " + this._format('00.0', (min - parseInt(min)) * 60) + "''";
      deg = parseInt(centerCopy.lat);
      min = (centerCopy.lat - deg) * 60;
      lat = deg + 'º ' + this._format('00', parseInt(min)) + "' " + this._format('00.0', (min - parseInt(min)) * 60) + "''";
    } else { // 'DD'
      lng = this._format('#0.00000', centerCopy.lng) + 'º';
      lat = this._format('##0.00000', centerCopy.lat) + 'º';
    }

    return L.Util.template(this.options.template, {
      x: (!this.options.latlngDesignators && centerCopy.lng_neg ? '-' : '') + lng + (this.options.latlngDesignators ? (centerCopy.lng_neg ? ' W' : ' E') : ''),
      y: (!this.options.latlngDesignators && centerCopy.lat_neg ? '-' : '') + lat + (this.options.latlngDesignators ? (centerCopy.lat_neg ? ' S' : ' N') : '')
    });
  },

  _format: function (m, v) {
    if (!m || isNaN(+v)) {
      return v; //return as it is.
    }
    //convert any string to number according to formation sign.
    var v = m.charAt(0) == '-' ? -v : +v;
    var isNegative = v < 0 ? v = -v : 0; //process only abs(), and turn on flag.

    //search for separator for grp & decimal, anything not digit, not +/- sign, not #.
    var result = m.match(/[^\d\-\+#]/g);
    var Decimal = (result && result[result.length - 1]) || '.'; //treat the right most symbol as decimal
    var Group = (result && result[1] && result[0]) || ','; //treat the left most symbol as group separator

    //split the decimal for the format string if any.
    var m = m.split(Decimal);
    //Fix the decimal first, toFixed will auto fill trailing zero.
    v = v.toFixed(m[1] && m[1].length);
    v = +(v) + ''; //convert number to string to trim off *all* trailing decimal zero(es)

    //fill back any trailing zero according to format
    var pos_trail_zero = m[1] && m[1].lastIndexOf('0'); //look for last zero in format
    var part = v.split('.');
    //integer will get !part[1]
    if (!part[1] || part[1] && part[1].length <= pos_trail_zero) {
      v = (+v).toFixed(pos_trail_zero + 1);
    }
    var szSep = m[0].split(Group); //look for separator
    m[0] = szSep.join(''); //join back without separator for counting the pos of any leading 0.

    var pos_lead_zero = m[0] && m[0].indexOf('0');
    if (pos_lead_zero > -1) {
      while (part[0].length < (m[0].length - pos_lead_zero)) {
        part[0] = '0' + part[0];
      }
    } else if (+part[0] == 0) {
      part[0] = '';
    }

    v = v.split('.');
    v[0] = part[0];

    //process the first group separator from decimal (.) only, the rest ignore.
    //get the length of the last slice of split result.
    var pos_separator = (szSep[1] && szSep[szSep.length - 1].length);
    if (pos_separator) {
      var integer = v[0];
      var str = '';
      var offset = integer.length % pos_separator;
      for (var i = 0, l = integer.length; i < l; i++) {

        str += integer.charAt(i); //ie6 only support charAt for sz.
        //-pos_separator so that won't trail separator on full length
        if (!((i - offset + 1) % pos_separator) && i < l - pos_separator) {
          str += Group;
        }
      }
      v[0] = str;
    }

    v[1] = (m[1] && v[1]) ? Decimal + v[1] : "";
    return (isNegative ? '-' : '') + v[0] + v[1]; //put back any negation and combine integer and fraction.
  }
});

L.Map.mergeOptions({
  MapCenterCoordControl: false
});

L.Map.addInitHook(function () {
  if (this.options.MapCenterCoordControl) {
    this.MapCenterCoordControl = new L.Control.MapCenterCoord();
    this.addControl(this.MapCenterCoordControl);
  }
});

L.control.mapCenterCoord = function (options) {
  return new L.Control.MapCenterCoord(options);
};

Below is an example of how to easily determine the center of the map.以下是如何轻松确定 map 中心的示例。 This is a reworked one of my examples so it's more goodies but you can simplify yourself.这是我的示例之一,因此它是更多的好东西,但您可以简化自己。

 /* eslint-disable no-undef */ /** * Obtaining coordinates of the visible map */ // config map let config = { minZoom: 7, maxZomm: 18, }; // magnification with which the map will start const zoom = 18; // co-ordinates const lat = 52.22977; const lng = 21.01178; // calling map const map = L.map('map', config).setView([lat, lng], zoom); // Used to load and display tile layers on the map // Most tile servers require attribution, which you can set under `Layer` L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', }).addTo(map); const markerPlace = document.querySelector('.marker-position'); // on drag end map.on('dragend', setRentacle); // second option, by dragging the map map.on('dragstart', updateInfo); // on zoom end map.on('zoomend', setRentacle); // update info about bounds when site loaded document.addEventListener('DOMContentLoaded', function() { const bounds = map.getBounds(); updateInfo(bounds._northEast, bounds._southWest); }); // set rentacle function function setRentacle() { const bounds = map.getBounds(); // update info about bounds updateInfo(bounds._northEast, bounds._southWest); // set rentacle L.rectangle(bounds, { color: randomColor(), weight: 20, fillOpacity: 0.1, }).addTo(map); // set map map.fitBounds(bounds); } // generate random color function randomColor() { return `#${Math.floor(Math.random() * 16777215).toString(16)}`; } function updateInfo(north, south) { const center = map.getCenter(); markerPlace.textContent = south === undefined? 'We are moving the map...': `Center: ${center}, SouthWest: ${north}, NorthEast: ${south}`; }
 @import url(https://fonts.googleapis.com/css?family=Lato&display=swap); *, :after, :before { box-sizing: border-box; padding: 0; margin: 0; } html { height: 100%; } body, html, #map { width: 100%; height: 100%; margin: 0; padding: 0; } #map:before { position: absolute; content: "+"; font-size: 3rem; font-weight: 400; display: flex; justify-content: center; align-items: center; color: red; z-index: 9999999; top: 0; left: 0; right: 0; bottom: 0; margin: auto; border: 10px; } body { position: relative; height: 100%; font-family: Lato, sans-serif; min-height: 100%; padding: 0; margin: 0; }.marker-position { position: absolute; bottom: 0; left: 0; z-index: 999; padding: 20px 10px; font-size: 10px; background-color: #fff; }
 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" /> <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script> <div class="marker-position"></div> <div id="map"></div>

As for your problem, console.log is working.至于您的问题,console.log 正在运行。 I tested locally and the coordinates appear.我在本地测试,坐标出现了。

onAdd: function(map) {
  ...
  this._container.innerHTML = this._getMapCenterCoord();
  // works
  console.log(this._getMapCenterCoord());
  return this._container;
},

_onMapMoveEnd: function(e) {
  ...
  // update coordinates
  this._container.innerHTML = this._getMapCenterCoord();
  // works
  console.log(this._getMapCenterCoord());
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM