Feature Your Map beta

get poi data from osm

目前为 2024-04-03 提交的版本。查看 最新版本

// ==UserScript==
// @name         Feature Your Map beta
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  get poi data from osm
// @author       KaKa
// @match        https://map-making.app/maps/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_setClipboard
// @license      MIT
// @icon         https://www.google.com/s2/favicons?domain=geoguessr.com
// ==/UserScript==

(function() {
    'use strict';


    const API_URL = "https://overpass-api.de/api/interpreter";

    async function fetchData(query, isString,feature) {
        const requestBody = isString ?
              `[out:json][timeout:180]; area[name="${query}"]; (nwr(area)[${feature}]; );out geom;` :
        `[bbox:${query[1]},${query[0]},${query[3]},${query[2]}][out:json][timeout:180] ;( nwr[${feature}](${query[1]},${query[0]},${query[3]},${query[2]}););out geom;`;
        const response = await fetch(API_URL, {
            method: "POST",
            body: "data=" + encodeURIComponent(requestBody),
        });

        if (!response.ok) {
            throw new Error("Network response was not ok");
        }

        return response.json();
    }

    async function getData(query) {
        try {
            const js = {
                "name": "",
                "customCoordinates": [],
                "extra": {
                    "tags": {},
                    "infoCoordinates": []
                }
            };
            for (let feature of features) {
                let requests = [];
                let elements = [];
                if (typeof query === 'string') {
                    requests.push(fetchData(query, true, feature[1]));
                } else {
                    requests = query.map(b => fetchData(b, false, feature[1]));
                }

                const responses = await Promise.all(requests);

                responses.forEach(response => {
                    if (response.elements && response.elements.length > 0) {
                        elements.push(...response.elements);
                    }
                });
                writeData(elements, feature[0],js);

            }
            GM_setClipboard(JSON.stringify(js));
            alert("JSON data has been copied to your clipboard!");

        } catch (error) {
            console.error("Error fetching data:", error);
        }
    }

    function writeData(coordinates, feature,js) {
        for (let i = 0; i < coordinates.length; i++) {
            if (coordinates[i].geometry) {
                let nodes = coordinates[i].geometry;
                let randomIndex = Math.floor(Math.random() * nodes.length);
                let randomCoordinate = nodes[randomIndex];
                let tag = coordinates[i].tags && coordinates[i].tags.highway ? coordinates[i].tags.highway : feature;
                js.customCoordinates.push({
                    "lat": randomCoordinate.lat,
                    "lng": randomCoordinate.lon,
                    "extra": {
                        "tags": [tag,feature]
                    }
                });
            }else if (!isCoordinateExists(js.customCoordinates, coordinates[i].lat, coordinates[i].lon)) {
                js.customCoordinates.push({
                    "lat": coordinates[i].lat,
                    "lng": coordinates[i].lon,
                    "extra": {
                        "tags": [feature]
                    }
                });
            }
        }
    }

    function isCoordinateExists(coordinates, lat, lon) {
        for (let i = 0; i < coordinates.length; i++) {
            if (coordinates[i].lat === lat && coordinates[i].lng === lon) {
                return true;
            }
        }

        return false;
    }

    function getInput() {
        const option = confirm('Do you want to upload a Geojson file? If you click "Cancel",you will need to enter a location name');

        if (option) {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.geojson';
            input.addEventListener('change', event => {
                const file = event.target.files[0];
                if (file) {
                    readFile(file);
                    document.body.removeChild(input);
                }
            });

            document.body.appendChild(input);
        } else {
            const query = prompt('Please enter a location name(eg:Paris)');
            getData(query);
        }
    }

    function readFile(file) {
        const reader = new FileReader();

        reader.onload = function(event) {
            const jsonContent = event.target.result;

            try {
                const data = JSON.parse(jsonContent);

                if (data.features && data.features.length > 0) {
                    const boundary = data.features.map(feature => feature.bbox);
                    getData(boundary);
                } else {
                    console.error('Invalid Geojson format.');
                }
            } catch (error) {
                console.error('Error parsing Geojson:', error);
            }
        };

        reader.readAsText(file);
    }

    let features=[]
    var mainButtonContainer = document.createElement('div');
    mainButtonContainer.style.position = 'fixed';
    mainButtonContainer.style.right = '20px';
    mainButtonContainer.style.top = '20px';
    document.body.appendChild(mainButtonContainer);

    var buttonContainer = document.createElement('div');
    buttonContainer.style.position = 'fixed';
    buttonContainer.style.right = '20px';
    buttonContainer.style.bottom = '60px';
    buttonContainer.style.display = 'none';
    document.body.appendChild(buttonContainer);

    function createCheckbox(text, tags) {
        var label = document.createElement('label');
        var checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.value = text;
        checkbox.name = 'tags';
        checkbox.id = tags;
        label.appendChild(checkbox);
        label.appendChild(document.createTextNode(text));
        buttonContainer.appendChild(label);
        return checkbox;
    }

    var triggerButton = document.createElement('button');
    triggerButton.textContent = 'Star Featuring';
    triggerButton.addEventListener('click', function() {
        var checkboxes = document.getElementsByName('tags');
        for (var i=0; i<checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                if (!features.includes(checkboxes[i].id)) {
                    features.push([checkboxes[i].value,checkboxes[i].id]);
                }
            }
        }
        getInput();
    });
    buttonContainer.appendChild(triggerButton);

    var mainButton = document.createElement('button');
    mainButton.textContent = 'Feature Your Map';
    mainButton.addEventListener('click', function() {
        if (buttonContainer.style.display === 'none') {
            buttonContainer.style.display = 'block';
        } else {
            buttonContainer.style.display = 'none';
        }
    });
    mainButtonContainer.appendChild(mainButton);

    createCheckbox('bridge', '"bridge"="yes"');
    createCheckbox('bus stop', '"highway"="bus_stop"');

})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址