OpenStreetMap, eine Alternative zu Google Maps

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.

JavaScript:
osm.js JavaScript (1,65 kByte) 16.10.2021 23:21
// coding: utf-8
/** Created by: Udo Schmal | https://www.gocher.me/ */
(function () {
  'use strict';

  function OpenStreetMap (item) {
    item.style.width = '100%';
    item.style.height = '300px';
    let lat = item.dataset.lat;
    let lon = item.dataset.lon;
    let zoom = item.dataset.zoom || 18;
    // initialize map
    let map = L.map(item).setView([lat, lon], zoom);
    if (map) {
      // set map tiles source
      L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
        maxZoom: 21,
      }).addTo(map);
      let title = item.dataset.title;
      let info = item.dataset.info;
      // add marker to the map
      let marker = L.marker([lat, lon]).addTo(map);
      // add popup to the marker
      marker.bindPopup("<strong>" + title + "</strong><br />" + info);
    }
  }

  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);
  }

  function init() {
    var maps = document.querySelectorAll('.map');
    for (var i=0; i < maps.length; i++) {
      new OpenStreetMap(maps[i]);
    }
  }

})();






HTML:
osm.htm HTML (1,42 kByte) 10.09.2021 15:37
<!DOCTYPE html >
<html lang="de">
  <head>
    <meta charset="utf-8" />
    <title>OpenStreetMap</title>
    <link rel="stylesheet" href="leaflet.css" />
    <script src="leaflet.min.js"></script>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' https://nominatim.openstreetmap.org/; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://tile.openstreetmap.org/ " />
  </head>
  <body>
    <form id="geoRequest"><label for="name" style="display:inline-block; width:100px;text-align:right">Name:</label><input type="text" id="name" value="Udo Schmal" /><br /><label for="street" style="display:inline-block; width:100px;text-align:right">Strasse:</label><input type="text" name="street" value="Olvengraben 41" /><br /><label for="city" style="display:inline-block; width:100px;text-align:right">City:</label><input type="text" name="city" value="Geldern" /><br /><label for="postalcode" style="display:inline-block; width:100px;text-align:right">Postalcode:</label><input type="text" name="postalcode" value="47608" /><br /><label for="country" style="display:inline-block; width:100px;text-align:right">Country:</label><input type="text" name="country" value="de" /><br /><button type="submit" id="button">add marker</button><br /></form>
    <div id="mapDiv" style="width: 800px; height: 500px; max-width:100%;"></div>
    <script src="osm-form.js"></script>
  </body>
</html>
JavaScript:
osm-form.js JavaScript (3,81 kByte) 10.09.2021 15:40
// coding: utf-8
/** Created by: Udo Schmal | https://www.gocher.me/ */
(function () {
  'use strict';

  function OpenStreetMap (id) {
    this.id = id;
    this.map = null;
    let mapDiv = document.getElementById('mapDiv');
    mapDiv.style.width = '800px';
    mapDiv.style.height = '500px';
    mapDiv.style.maxWidth = '100%';
  }

  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();
    },
    createMap: function (lat, lon, zoom) {
      // initialize map
      this.map = L.map(this.id).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/">OpenStreetMap</a> contributors',
        maxZoom: 18,
      }).addTo(this.map);
    },
    setMarker: function (lat, lon, title, text) {
      if (this.map) {
        // add marker to the map
        marker = L.marker([lat, lon]).addTo(this.map);
        // add popup to the marker
        marker.bindPopup("<strong>" + title + "</strong><br />" + text);
      }
    },
    init: function (obj) {
      var self = this;
      this.requestGeo(obj, function(lat, lon, text) {
        self.createMap(lat, lon, 11);
      });
    },
    addItem: function (obj, title, text) {
      var self = this;
      var body = text;
      this.requestGeo(obj,function(lat, lon, text) {
        self.setMarker(lat, lon, title, body || text);
      });
    },
    addItems: function (arr) {
      var self = this;
      arr.forEach(function (item) {
        var title = item.name;
        var body = item.street + '<br />' +
          item.postalcode + ' ' + item.city;
        self.requestGeo(item,function(lat, lon, text) {
          self.setMarker(lat, lon, title, body || text);
        });
      });
    }
  };

  var osm = new OpenStreetMap('mapDiv');
  osm.init({country:'de', city:'Geldern', postalcode:'47608'});
  var items = [
    {name: "Udo Schmal", street: "Olvengraben 41", country: 'de', city: 'Geldern', postalcode: '47608'}
  ];
  osm.addItems(items);
  function onSubmit(event) {
    event.preventDefault();
    var name = '', data = {};
    var els = document.getElementById('geoRequest').elements;
    for (var i=0; i < els.length; i++) {
      if (els[i].name && els[i].value) {
        data[els[i].name] = els[i].value;
      } else if (els[i].id && els[i].id=="name") {
        name = els[i].value;
      }
    }
    osm.addItem(data, name, null);
  }
  var btn = document.getElementById("button");
  btn.addEventListener('click', onSubmit);

})();

Author: , published: , last modified:

Kontakt

Udo Schmal

Udo Schmal
Softwareentwickler
Olvengraben 41
47608 Geldern
Nordrhein-Westfalen
Germany





+49 2831 9776557
+49 1575 0663676
+49 2831 1328709
SMS
WhatsApp

Google Maps-Profile
Instagram Profile
vCard 3.0

Service Infos

CMS Info Product Name:
UDOs Webserver
Version:
0.5.0.104
Description:
All in one Webserver
Copyright:
Udo Schmal
Compilation:
Sat, 9. Oct 2021 15:16:12
Development Info Compiler:
Free Pascal FPC 3.3.1
compiled for:
OS:Linux, CPU:x86_64
System Info OS:
Ubuntu 20.04.3 LTS (Focal Fossa)
Hardware Info Model:
Hewlett-Packard HP Pavilion dv7 Notebook PC
CPU Name:
Intel(R) Core(TM) i5-2450M CPU @ 2.50GHz
CPU Type:
x86_64, 1 physical CPU(s), 2 Core(s), 4 logical CPU(s), 800.000 MHz