Как добавить геолокацию в форму GeoDjango? - PullRequest
3 голосов
/ 23 сентября 2019

Мне нужно настроить способ добавления точки на карту с помощью GeoDjango.

Я разработал собственный виджет, шаблон и js.

widgets.py

class CustomGeometryWidget(BaseGeometryWidget):
    template_name = 'geosources/widget/customgeometrywidget.html'
    map_srid = 3857

    class Media:
        css = {
            'all': (
                'gis/css/ol3.css',
            )
        }
        js = (
            'js/customgeometrywidget.js',
        )

    def serialize(self, value):
        return value.json if value else ''

    def deserialize(self, value):
        geom = super().deserialize(value)
        # GeoJSON assumes WGS84 (4326). Use the map's SRID instead.
        if geom and json_regex.match(value) and self.map_srid != 4326:
            geom.srid = self.map_srid
        return geom

customgeometrywidget.html

{% load i18n l10n %}
<style type="text/css">{% block map_css %}{% get_current_language_bidi as LANGUAGE_BIDI %}
    #{{ id }}_map { width: {{ map_width }}px; height: {{ map_height }}px; }
    #{{ id }}_map .aligned label { float: inherit; }
    #{{ id }}_div_map { position: relative; vertical-align: top; float: {{ LANGUAGE_BIDI|yesno:"right,left" }}; }
    {% if not display_raw %}#{{ id }} { display: none; }{% endif %}
    {% endblock %}
</style>

<div class="gealogos-wrapper" id="{{ id }}_div_map">
    <div class="gealogos-map" id="{{ id }}_map"></div>

    <div class="geolocation" id="geolocateme">
      <button class="btn geolocation-button">
        <i class="fas fa-globe"></i>
      </button>
    </div>

    {% if not disabled %}
    <div class="delete-geometry">
      <span class="">
        <a class="clear_features btn delete-geometry-button" href="javascript:{{ module }}.clearFeatures()">
          <i class="fas fa-trash"></i>
          {% trans "" %}
        </a>
      </span>
    </div>
    {% endif %}
    {% if display_raw %}<p>{% trans "Debugging window (serialized value)" %}</p>{% endif %}
    <textarea id="{{ id }}" class="vSerializedField required" cols="150" rows="10" name="{{ name }}">{{ serialized }}</textarea>
    <script type="text/javascript">
        {% block map_options %}var map_options = {};{% endblock %}
        {% block base_layer %}
            var base_layer = new ol.layer.Tile({
              source: new ol.source.XYZ({
                  attributions: 'Theme created by <a href="http://massimilianomoraca.it/" target ="_blank">Massimiliano Moraca</a> with <a href="https://www.mapbox.com/" target ="_blank">MapBox</a>',
                  url: 'https://api.mapbox.com/styles/v1/maxdragonheart/ck0l7j9cx27df1clhcyok70mk/tiles/256/{z}/{x}/{y}'
                        + '?access_token=pk.eyJ1IjoibWF4ZHJhZ29uaGVhcnQiLCJhIjoiY2p4a2k3a2twMmF2aDN4czhwMzBoZ2x1eCJ9.upAxT3LK0NCiP_jBcErzNw'
                }),
            });
        {% endblock %}
        {% block options %}var options = {
            base_layer: base_layer,
            geom_name: '{{ geom_type }}',
            id: '{{ id }}',
            map_id: '{{ id }}_map',
            map_options: map_options,
            map_srid: {{ map_srid|unlocalize }},
            name: '{{ name }}'
        };
        {% endblock %}
        var {{ module }} = new MapWidget(options);
///// GEOLOCATION /////
        var geolocation = new ol.Geolocation({
              projection: map.getView().getProjection(),
              tracking: false,
              trackingOptions: {
                enableHighAccuracy: true,
                maximumAge: 5000
              }
            });
          var button = document.getElementById('geolocateme');
          var handleGetPosition = function(e) {
          var trackingwasalreadyon = geolocation.getTracking();
          console.log(trackingwasalreadyon);
          if(trackingwasalreadyon){
              geolocation.setTracking(false);
              } else
              { geolocation.setTracking(true); getPosition();
              }
          };
          button.addEventListener('click', handleGetPosition, false);
          button.addEventListener('touchstart', handleGetPosition, false);
        function getPosition() {
            var positionFeature = new ol.Feature();
            positionFeature.setStyle(new ol.style.Style({
              image: new ol.style.Circle({
                radius: 6,
                fill: new ol.style.Fill({
                  color: '#fa0000'
                }),
                stroke: new ol.style.Stroke({
                  color: '#fff',
                  width: 2
                }),
              }),
            }));
            geolocation.on('change:position', function() {
              var pos = geolocation.getPosition();
              positionFeature.setGeometry(pos ?
                  new ol.geom.Point(pos) : null);
              view.setCenter(pos);
              view.setZoom(12);
            });

            new ol.layer.Vector({
              map: map,
              source: new ol.source.Vector({
                features: [
                  positionFeature,
                ]
              })
            });
        };

    </script>
</div>

JS похож на OLMapWidget.js, я изменил масштабдобавьте геокодер.

customgeometrywidget.js

var GeometryTypeControl = function(opt_options) {
    'use strict';
    // Map control to switch type when geometry type is unknown
    var options = opt_options || {};

    var element = document.createElement('div');
    element.className = 'switch-type type-' + options.type + ' ol-control ol-unselectable';
    if (options.active) {
        element.className += " type-active";
    }

    var self = this;
    var switchType = function(e) {
        e.preventDefault();
        if (options.widget.currentGeometryType !== self) {
            options.widget.map.removeInteraction(options.widget.interactions.draw);
            options.widget.interactions.draw = new ol.interaction.Draw({
                features: options.widget.featureCollection,
                type: options.type
            });
            options.widget.map.addInteraction(options.widget.interactions.draw);
            var className = options.widget.currentGeometryType.element.className.replace(/ type-active/g, '');
            options.widget.currentGeometryType.element.className = className;
            options.widget.currentGeometryType = self;
            element.className += " type-active";
        }
    };

    element.addEventListener('click', switchType, false);
    element.addEventListener('touchstart', switchType, false);

    ol.control.Control.call(this, {
        element: element
    });
};
ol.inherits(GeometryTypeControl, ol.control.Control);

// TODO: allow deleting individual features (#8972)
(function() {
    'use strict';
    var jsonFormat = new ol.format.GeoJSON();

    function MapWidget(options) {
        this.map = null;
        this.interactions = {draw: null, modify: null};
        this.typeChoices = false;
        this.ready = false;

        // Default options
        this.options = {
            default_lat: 0,
            default_lon: 0,
            default_zoom: 2,
            is_collection: options.geom_name.indexOf('Multi') > -1 || options.geom_name.indexOf('Collection') > -1
        };

        // Altering using user-provided options
        for (var property in options) {
            if (options.hasOwnProperty(property)) {
                this.options[property] = options[property];
            }
        }
        if (!options.base_layer) {
            this.options.base_layer = new ol.layer.Tile({
              source: new ol.source.XYZ({
                  attributions: 'Theme created by <a href="http://massimilianomoraca.it/" target ="_blank">Massimiliano Moraca</a> with <a href="https://www.mapbox.com/" target ="_blank">MapBox</a>',
                  url: 'https://api.mapbox.com/styles/v1/maxdragonheart/ck0l7j9cx27df1clhcyok70mk/tiles/256/{z}/{x}/{y}'
                        + '?access_token=pk.eyJ1IjoibWF4ZHJhZ29uaGVhcnQiLCJhIjoiY2p4a2k3a2twMmF2aDN4czhwMzBoZ2x1eCJ9.upAxT3LK0NCiP_jBcErzNw'
                }),
            });
        }

        this.map = this.createMap();
        this.featureCollection = new ol.Collection();
        this.featureOverlay = new ol.layer.Vector({
            map: this.map,
            source: new ol.source.Vector({
                features: this.featureCollection,
                useSpatialIndex: false // improve performance
            }),
            updateWhileAnimating: true, // optional, for instant visual feedback
            updateWhileInteracting: true // optional, for instant visual feedback
        });

        // Populate and set handlers for the feature container
        var self = this;
        this.featureCollection.on('add', function(event) {
            var feature = event.element;
            feature.on('change', function() {
                self.serializeFeatures();
            });
            if (self.ready) {
                self.serializeFeatures();
                if (!self.options.is_collection) {
                    self.disableDrawing(); // Only allow one feature at a time
                }
            }
        });

        var initial_value = document.getElementById(this.options.id).value;
        if (initial_value) {
            var features = jsonFormat.readFeatures('{"type": "Feature", "geometry": ' + initial_value + '}');
            var extent = ol.extent.createEmpty();
            features.forEach(function(feature) {
                this.featureOverlay.getSource().addFeature(feature);
                ol.extent.extend(extent, feature.getGeometry().getExtent());
            }, this);
            // Center/zoom the map
            this.map.getView().fit(extent, {maxZoom: this.options.default_zoom});
        } else {
            this.map.getView().setCenter(this.defaultCenter());
        }
        this.createInteractions();
        if (initial_value && !this.options.is_collection) {
            this.disableDrawing();
        }
        this.ready = true;
    }

    MapWidget.prototype.createMap = function() {
        var map = new ol.Map({
            controls: this.options.controls,
            target: this.options.map_id,
            layers: [this.options.base_layer],
            view: new ol.View({
                zoom: this.options.default_zoom
            })
        });

        /// GEOCODER
        var geocoder = new Geocoder('nominatim', {
          provider: 'osm',
          lang: 'en',
          placeholder: 'Search a city',
          limit: 3,
          debug: false,
          autoComplete: true,
          keepOpen: true,
        });
        map.addControl(geocoder);

        return map;

    };

    MapWidget.prototype.createInteractions = function() {
        // Initialize the modify interaction
        this.interactions.modify = new ol.interaction.Modify({
            features: this.featureCollection,
            deleteCondition: function(event) {
                return ol.events.condition.shiftKeyOnly(event) &&
                    ol.events.condition.singleClick(event);
            }
        });

        // Initialize the draw interaction
        var geomType = this.options.geom_name;
        if (geomType === "Unknown" || geomType === "GeometryCollection") {
            // Default to Point, but create icons to switch type
            geomType = "Point";
            this.currentGeometryType = new GeometryTypeControl({widget: this, type: "Point", active: true});
            this.map.addControl(this.currentGeometryType);
            this.map.addControl(new GeometryTypeControl({widget: this, type: "LineString", active: false}));
            this.map.addControl(new GeometryTypeControl({widget: this, type: "Polygon", active: false}));
            this.typeChoices = true;
        }
        this.interactions.draw = new ol.interaction.Draw({
            features: this.featureCollection,
            type: geomType
        });

        this.map.addInteraction(this.interactions.draw);
        this.map.addInteraction(this.interactions.modify);
    };

    MapWidget.prototype.defaultCenter = function() {
        var center = [this.options.default_lon, this.options.default_lat];
        if (this.options.map_srid) {
            return ol.proj.transform(center, 'EPSG:4326', this.map.getView().getProjection());
        }
        return center;
    };

    MapWidget.prototype.enableDrawing = function() {
        this.interactions.draw.setActive(true);
        if (this.typeChoices) {
            // Show geometry type icons
            var divs = document.getElementsByClassName("switch-type");
            for (var i = 0; i !== divs.length; i++) {
                divs[i].style.visibility = "visible";
            }
        }
    };

    MapWidget.prototype.disableDrawing = function() {
        if (this.interactions.draw) {
            this.interactions.draw.setActive(false);
            if (this.typeChoices) {
                // Hide geometry type icons
                var divs = document.getElementsByClassName("switch-type");
                for (var i = 0; i !== divs.length; i++) {
                    divs[i].style.visibility = "hidden";
                }
            }
        }
    };

    MapWidget.prototype.clearFeatures = function() {
        this.featureCollection.clear();
        // Empty textarea widget
        document.getElementById(this.options.id).value = '';
        this.enableDrawing();
    };

    MapWidget.prototype.serializeFeatures = function() {
        // Three use cases: GeometryCollection, multigeometries, and single geometry
        var geometry = null;
        var features = this.featureOverlay.getSource().getFeatures();
        if (this.options.is_collection) {
            if (this.options.geom_name === "GeometryCollection") {
                var geometries = [];
                for (var i = 0; i < features.length; i++) {
                    geometries.push(features[i].getGeometry());
                }
                geometry = new ol.geom.GeometryCollection(geometries);
            } else {
                geometry = features[0].getGeometry().clone();
                for (var j = 1; j < features.length; j++) {
                    switch (geometry.getType()) {
                    case "MultiPoint":
                        geometry.appendPoint(features[j].getGeometry().getPoint(0));
                        break;
                    case "MultiLineString":
                        geometry.appendLineString(features[j].getGeometry().getLineString(0));
                        break;
                    case "MultiPolygon":
                        geometry.appendPolygon(features[j].getGeometry().getPolygon(0));
                    }
                }
            }
        } else {
            if (features[0]) {
                geometry = features[0].getGeometry();
            }
        }
        document.getElementById(this.options.id).value = jsonFormat.writeGeometry(geometry);
    };

    window.MapWidget = MapWidget;
})();

Как вы можете видеть в конце customgeometrywidget.html, есть скрипт для геолокации.Этот скрипт отлично работает на простой карте, в которой нет необходимости добавлять какие-либо геометрии, но когда я использую его внутри customgeometrywidget.html, я вижу эту ошибку в консоли:

Uncaught ReferenceError: карта не определена

Карта отображается, но если я нажму на кнопку геолокации, ничего не произойдет;можно добавить и удалить точку.

Мои навыки работы с JavaScript самые низкие, и я не могу решить эту проблему.Является ли лучшая стратегия для добавления геолокации и помочь пользователю добавить геометрию?

...