OpenStreetMap Marker

Mit einem simpelen Beispiel möche ich hier demonstrieren dass mit wenigen Zeilen Code mit OpenStreetMap bereits eine Kartendarstellung und in Verbindung mit Leaflet eine Positionsmarke möglich ist, selbst das Ermitteln einer Position zu einer Adresse ist unter zur Hilfename von nominatim.openstreetmap.org möglich.







HTML:
osm-form.htm HTML (956 Bytes) 03.07.2024 20:19
<!DOCTYPE html >
<html lang="de">
  <head>
    <meta charset="utf-8" />
    <title>OpenStreetMap</title>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: https://nominatim.openstreetmap.org/; img-src 'self' data: https://tile.openstreetmap.org/" />
  </head>
  <body>
    <form id="geoRequest"><label for="name">Name:</label><input type="text" name="name" value="Udo Schmal" /><br /><label for="street">Street:</label><input type="text" name="street" value="Ellerndiek 26" /><br /><label for="city">City:</label><input type="text" name="city" value="Schleswig" /><br /><label for="postalcode">Postalcode:</label><input type="text" name="postalcode" value="24837" /><br /><label for="country">Country:</label><input type="text" name="country" value="de" /><br /><button type="submit">add marker</button><br /></form>
    <div id="mapDiv" data-type="osm"></div>
    <script src="osm-form.js"></script>
  </body>
</html>
JavaScript:
osm-form.js JavaScript (4,41 kByte) 03.07.2024 19:57
// coding: utf-8
/*! Created by: Udo Schmal | https://www.gocher.me/ */
(function () {
  'use strict';

  function OpenStreetMap (id, pos, zoom) {
    this.id = id;
    this.map = null;
    let mapDiv = document.getElementById(id);
    mapDiv.style.width = '100%';
    mapDiv.style.height = '300px';
    var self = this;
    this.requestGeo(pos, function(lat, lon, text) {
      // initialize map
      self.map = L.map(self.id, {scrollWheelZoom: false}).setView([lat, lon], zoom);
      // set map tiles source
      L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/" target="_blank" rel="nofollow noopener noreferrer">OpenStreetMap</a> and contributors <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="nofollow noopener noreferrer">CC-BY-SA</a>',
        maxZoom: 18,
      }).addTo(self.map);
    });
  }

  OpenStreetMap.prototype = {
    requestGeo: function (obj, callback) {
      /* own Server installation http://nominatim.org/release-docs/latest/admin/Installation/ */
      var url = "https://nominatim.openstreetmap.org/search.php";
      function serialize(obj) {
        var str = [];
        for (var p in obj)
          if (obj.hasOwnProperty(p) && (['street', 'country', 'city', 'postalcode'].indexOf(p) !== -1)) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
          }
        return str.join("&") + '&format=json';
      }
      url = url + '?' + serialize(obj);
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      //xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
      //xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST');
      //xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.responseType = 'json';
      xhr.addEventListener('load', function (event) {
        if (xhr.status === 200) {
          if (xhr.response && xhr.response[0]) {
            var lat = xhr.response[0].lat;
            var lon = xhr.response[0].lon;
            var text = xhr.response[0].display_name;
            callback(lat, lon, text);
          }
        }
      });
      xhr.send();
    },
    setMarker: function (lat, lon, title, text) {
      if (this.map) {
        // add marker to the map
        let marker = L.marker([lat, lon]).addTo(this.map);
        // add popup to the marker
        marker.bindPopup("<strong>" + title + "</strong><br />" + text);
        // center map at this marker
        this.map.panTo(new L.LatLng(lat, lon));
      }
    },
    addItem: function (item) {
      var self = this;
      var title = item.name;
      var body = item.street + '<br />' +
          item.postalcode + ' ' + item.city;
      this.requestGeo(item, function(lat, lon, text) {
        self.setMarker(lat, lon, title, body || text);
      });
    },
    addItems: function (arr) {
      var self = this;
      arr.forEach(function (item) {
        self.addItem(item);
      });
    }
  };

  var form = document.querySelector('form#geoRequest');
  let mapDiv = document.getElementById('mapDiv');
  if (form && mapDiv) {
    function init() {
      var osm = new OpenStreetMap('mapDiv', {country:'de', city:'Geldern', postalcode:'47608'}, 11);
      osm.addItems([
        {name: "Udo Schmal", street: "Ellerndiek 26", country: 'de', city: 'Schleswig', postalcode: '24837'}
      ]);

      form.addEventListener('submit', function (event) {
        event.preventDefault();
        var data = {};
        for ( var i = 0; i < form.elements.length; i++ ) {
          let el = form.elements[i];
          if (el.name && el.value) {
            data[el.name] = el.value;
          }
        }
        osm.addItem(data);
      });
    }

    if (!document.getElementById('leaflet.css')) {
      var style = document.createElement('link');
      style.id = 'leaflet.css';
      style.type = 'text/css';
      style.rel = 'stylesheet';
      style.href = '/code/OpenStreetMap/leaflet.css';
      document.head.appendChild(style);
    }
    if (!document.getElementById('leaflet.js')) {
      var script = document.createElement('script');
      script.id = 'leaflet.js';
      script.src = '/code/OpenStreetMap/leaflet.min.js';
      script.addEventListener('load', init);
      document.body.appendChild(script);
    } else {
      init();
    }
  }

})();

Kontakt

Udo Schmal
Udo Schmal

Udo Schmal
Softwareentwickler
Ellerndiek 26
24837 Schleswig
Schleswig-Holstein
Germany




+49 4621 9785538
+49 1575 0663676
+49 4621 9785539
SMS
WhatsApp

Google Maps Profile
Instagram Profile
vCard 2.1, vCard 3.0, vCard 4.0

Service Infos

CMS Info

Product Name:
UDOs Webserver
Version:
0.5.1.217
Description:
All in one Webserver
Copyright:
Udo Schmal
Compilation:
Sun, 10. Nov 2024 00:22:34

Development Info

Compiler:
Free Pascal FPC 3.3.1
compiled for:
OS:Linux, CPU:x86_64

System Info

OS:
Ubuntu 22.04.5 LTS (Jammy Jellyfish)

Hardware Info

Model:
Hewlett-Packard HP Pavilion dm4 Notebook PC
CPU Name:
Intel(R) Core(TM) i5-2430M CPU @ 2.40GHz
CPU Type:
x86_64, 1 physical CPU(s), 2 Core(s), 4 logical CPU(s),  MHz