{"id":20339053,"url":"https://github.com/szczyglis-dev/map-markers-geocode","last_synced_at":"2025-04-11T23:12:32.609Z","repository":{"id":152686770,"uuid":"487139012","full_name":"szczyglis-dev/map-markers-geocode","owner":"szczyglis-dev","description":"[JS] JavaScript code examples illustrating how to use markers and geocoding on map APIs with two different engines: Google Maps and OpenStreetMap (using the Leaflet library - https://leafletjs.com). The examples include all the necessary libraries.","archived":false,"fork":false,"pushed_at":"2024-08-26T15:18:40.000Z","size":504,"stargazers_count":3,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-11T23:12:27.295Z","etag":null,"topics":["api","coordinates","example","examples","geocode","geocoding","geocoding-api","google-maps","google-maps-api","gps","gps-location","javascript","map","map-marker","maps","maps-api","markers","openstreetmap","openstreetmap-api","tutorial-code"],"latest_commit_sha":null,"homepage":"https://szczyglis.dev/map-markers-geocode","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/szczyglis-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-04-29T23:49:41.000Z","updated_at":"2024-08-26T15:18:06.000Z","dependencies_parsed_at":"2023-07-11T03:00:12.354Z","dependency_job_id":null,"html_url":"https://github.com/szczyglis-dev/map-markers-geocode","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/szczyglis-dev%2Fmap-markers-geocode","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/szczyglis-dev%2Fmap-markers-geocode/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/szczyglis-dev%2Fmap-markers-geocode/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/szczyglis-dev%2Fmap-markers-geocode/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/szczyglis-dev","download_url":"https://codeload.github.com/szczyglis-dev/map-markers-geocode/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248492876,"owners_count":21113163,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","coordinates","example","examples","geocode","geocoding","geocoding-api","google-maps","google-maps-api","gps","gps-location","javascript","map","map-marker","maps","maps-api","markers","openstreetmap","openstreetmap-api","tutorial-code"],"created_at":"2024-11-14T21:15:15.761Z","updated_at":"2025-04-11T23:12:32.592Z","avatar_url":"https://github.com/szczyglis-dev.png","language":"HTML","funding_links":["https://www.buymeacoffee.com/szczyglis"],"categories":[],"sub_categories":[],"readme":"Release: **1.0.12** | build: **2024.08.26** | **Javascript**\n\n# Map Markers \u0026 Geocode\n\nJavascript code examples illustrating how to use markers and geocoding on map APIs with two different engines: **Google Maps** and **OpenStreetMap** (using the Leaflet library - https://leafletjs.com). The examples include all the necessary libraries and are well-commented. The sample code can be utilized as a tutorial and training material for implementing your own solutions based on Google Maps or OpenStreetMap.\n\n**The repository contains working code examples in 2 files:**\n\n- `google_maps.html` - Demonstrates map marker placement and coordinate search with geocoding using Google Maps.\n- `open_street_map.html` - Demonstrates map marker placement and coordinate search with geocoding using OpenStreetMap.\n\nRemember to define your API key in the Google Maps example, which should be inserted at the bottom of the page in place of **{YOUR_API_KEY}**:\n\n```js\n\u003cscript src=\"https://maps.googleapis.com/maps/api/js?key={YOUR_API_KEY}\u0026callback=initMap\u0026v=weekly\" async\u003e\u003c/script\u003e\n```\n\n# Online example\n\nYou can also see the live examples in action in the online demo at:\n\n### https://szczyglis.dev/map-markers-geocode\n\n**INFO: The Google Maps online demo uses a developer API key with geocoding disabled.**\n\n![m1](https://user-images.githubusercontent.com/61396542/166086106-bcd24544-68ac-4e0b-8729-9c188af77ffa.png)\n\n![m2](https://user-images.githubusercontent.com/61396542/166086118-c1b33f7d-d8a0-4465-9b81-5b4f0e8d7a24.png)\n\n# Tutorial: how to use maps APIs?\n\n## Google Maps / Javascript\n\n**The example demonstrates how to place a draggable marker on the map, read the coordinates from its position, and use geocoding to find the coordinates of a specified location, then update the marker's position with the found coordinates.**\n\nFor the complete working example, including the form, libraries, and browser-ready code, see the file `google_maps.html` in the repository.\n\n```js\nlet map,\n    marker,\n    geocoder;\n\n// Initializes google map\nfunction initMap() {\n\n    console.log('Initializing map..');\n\n    // Initialize google geocoder\n    geocoder = new google.maps.Geocoder();\n\n    // Define map initial parameters\n    const myLatlng = new google.maps.LatLng(40.7127753, -74.0059728); // New York\n    const mapOptions = {\n        zoom: 6,\n        center: myLatlng,\n        mapTypeId: 'hybrid'\n    }\n\n    // Create map in \"map\" div\n    map = new google.maps.Map(document.getElementById('map'), mapOptions);\n\n    // Create marker\n    marker = new google.maps.Marker({\n        position: myLatlng,\n        map: map,\n        draggable: true,\n        title: \"Drag marker\"\n    });\n\n    // Add dragend listener to marker\n    marker.addListener(\"dragend\", () =\u003e {\n        const pos = marker.getPosition();\n        const lat = pos.lat();\n        const lng = pos.lng();\n        $('input[name=\"lat\"]').val(lat);\n        $('input[name=\"lng\"]').val(lng);\n        console.log('On marker drag end', lat, lng);\n    });\n\n    // Add click listener to map\n    google.maps.event.addListener(map, 'click', function (event) {\n        marker.setPosition(event.latLng);\n        $('input[name=\"lat\"]').val(event.latLng.lat());\n        $('input[name=\"lng\"]').val(event.latLng.lng());\n        console.log('On map click', event.latLng.lat(), event.latLng.lng());\n    });\n}\n\n// Executes geocode search\nfunction geocode(request) {\n    geocoder\n        .geocode(request)\n        .then((result) =\u003e {\n            const {results} = result;\n            map.setCenter(results[0].geometry.location);\n            map.setZoom(10);\n            marker.setPosition(results[0].geometry.location);\n            $('input[name=\"lat\"]').val(results[0].geometry.location.lat);\n            $('input[name=\"lng\"]').val(results[0].geometry.location.lng);\n            console.log('Geocode result', results);\n            return results;\n        })\n        .catch((e) =\u003e {\n            alert(\"Geocode error: \" + e);\n        });\n};\n\n// Updates marker position on map\nfunction updateMarker() {\n    const lat = $('input[name=\"lat\"]').val().trim();\n    const lng = $('input[name=\"lng\"]').val().trim();\n    if (lat.length != 0 \u0026\u0026 lng.length != 0) {\n        const latlng = new google.maps.LatLng(lat, lng);\n        marker.setPosition(latlng);\n        //map.setCenter(latlng); // \u003c --- uncomment if you want to center map in this place\n        console.log('Update marker position', lat, lng);\n    }\n};\n\n$(document).ready(function () {\n    // Refresh marker position when manual latitude update\n    $('body').on('change', 'input[name=\"lat\"]', function (e) {\n        updateMarker();\n    });\n\n    // Refresh marker position when manual longitude update\n    $('body').on('change', 'input[name=\"lng\"]', function (e) {\n        updateMarker();\n    });\n\n    // Run geocode search on form submit\n    $('body').on('submit', 'form[name=\"form\"]', function (e) {\n        e.preventDefault();\n        const query = $('input[name=\"search_query\"]').val();\n        if (query != '') {\n            geocode({address: query});\n        }\n    });\n});\n```\n\n## Open Street Map / Javascript\n\n**The example demonstrates how to place a draggable marker on the map, read the coordinates from its position, and use geocoding to find the coordinates of a specified location, then update the marker's position with the found coordinates.**\n\nFor the complete working example, including the form, libraries, and browser-ready code, see the file `open_street_map.html` in the repository.\n\n```js\nlet map,\n    marker;\n\n// Runs geocode search    \nfunction geocode(query) {\n    $.ajax({\n        url: 'https://nominatim.openstreetmap.org/search/' + query + '?format=json',\n        dataType: 'json',\n        method: 'GET'\n    })\n        .done(function (data) {\n            if (typeof data[0]['lat'] !== 'undefined' \u0026\u0026 typeof data[0]['lon'] !== 'undefined') {\n                const lat = data[0]['lat'];\n                const lng = data[0]['lon'];\n                $('input[name=\"lat\"]').val(lat);\n                $('input[name=\"lng\"]').val(lng);\n                setPoint(lat, lng);\n                console.log('Geocode result', lat, lng);\n            }\n        })\n        .fail(function (err) {\n            console.error(err);\n        });\n};\n\n// Click on map event handler\nfunction onMapClick(e) {\n    const lat = e.latlng.lat;\n    const lng = e.latlng.lng;\n    marker.setLatLng(e.latlng);\n    marker.setPopupContent(lat + \",\" + lng).openPopup();\n    $('input[name=\"lat\"]').val(lat);\n    $('input[name=\"lng\"]').val(lng);\n    console.log('On map click', lat, lng);\n}\n\n// Marker dragend event handler\nfunction onDragEnd(e) {\n    const lat = e.target._latlng.lat;\n    const lng = e.target._latlng.lng;\n    marker.setLatLng(e.target._latlng);\n    $('input[name=\"lat\"]').val(lat);\n    $('input[name=\"lng\"]').val(lng);\n    console.log('On marker drag end', lat, lng);\n}\n\n// Sets marker position\nfunction setPoint(lat, lng) {\n    marker.setLatLng(L.latLng(lat, lng));\n    map.setView([lat, lng], 12);\n}\n\n// Updates marker position on map\nfunction updateMarker() {\n    const lat = $('input[name=\"lat\"]').val().trim();\n    const lng = $('input[name=\"lng\"]').val().trim();\n    if (lat.length != 0 \u0026\u0026 lng.length != 0) {\n        setPoint(lat, lng);\n        // map.setView([lat, lng], 12); // \u003c --- uncomment if you want to center map in this place\n        console.log('Update marker position', lat, lng);\n    }\n};\n\nmap = L.map('map');\nmarker = L.marker([40.7127753, -74.0059728], {\n    draggable: 'false'\n});\nmarker.on('dragend', onDragEnd);\nmarker.bindPopup('0,0');\nmarker.addTo(map);\nmarker.setPopupContent('40.7127753,-74.0059728');\n\nL.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {\n    foo: 'bar',\n    attribution: '\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e'\n}).addTo(map),\nsetPoint(40.7127753, -74.0059728);\nmap.setZoom(6);\nmap.on('click', onMapClick);\n\n$(document).ready(function () {\n    // Refresh marker position when manual latitude update\n    $('body').on('change', 'input[name=\"lat\"]', function (e) {\n        updateMarker();\n    });\n\n    // Refresh marker position when manual longitude update\n    $('body').on('change', 'input[name=\"lng\"]', function (e) {\n        updateMarker();\n    });\n\n    // Run geocode search on form submit\n    $('body').on('submit', 'form[name=\"form\"]', function (e) {\n        e.preventDefault();\n        const query = $('input[name=\"search_query\"]').val();\n        if (query != '') {\n            geocode(query);\n        }\n    });\n});\n```\n___\n\n## Changelog\n\n**1.0.11** - Published first release. (2022-04-30)\n\n**1.0.12** - Updated docs. (2024-08-26)\n\n--- \n**Published examples are free to use, but if you like it, you can support my work by buying me a coffee ;)**\n\nhttps://www.buymeacoffee.com/szczyglis\n\n**Enjoy!**\n\nMIT License | 2022 Marcin 'szczyglis' Szczygliński\n\nhttps://github.com/szczyglis-dev/extended-dump-bundle\n\nhttps://szczyglis.dev\n\nContact: szczyglis@protonmail.com\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fszczyglis-dev%2Fmap-markers-geocode","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fszczyglis-dev%2Fmap-markers-geocode","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fszczyglis-dev%2Fmap-markers-geocode/lists"}