PatrickFrankAIU / LunarSparkle2403A

Repository for ITWEB 200 students, Term 2403A (Summer 2024)
0 stars 0 forks source link

Geolocation Feature #19

Closed PatrickFrankAIU closed 1 week ago

PatrickFrankAIU commented 1 week ago

Notes: This code will display a map and show your current location (so be careful what you share on screen), but of course it won't show any locations for Lunar Sparkle Jewelry Company, since there aren't any. This is sufficient for this exercise, but if you have any ideas for how we might simulate locations, let the instructor know and we'll look into it. :-)

HTML Code:

<h1>Find My Location</h1>
    <button onclick="getLocation()">Locate Me</button>
    <p id="location"></p>
    <a id="mapLink" href="#" target="_blank">View Location on OpenStreetMap</a>

JavaScript Code:

function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            } else {
                document.getElementById("location").innerHTML = "Geolocation is not supported by this browser.";
            }
        }

        function showPosition(position) {
            const latitude = position.coords.latitude;
            const longitude = position.coords.longitude;
            const location = "Latitude: " + latitude + "<br>Longitude: " + longitude;

            document.getElementById("location").innerHTML = location;
            document.getElementById("mapLink").href = `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}&zoom=15`;
        }

        function showError(error) {
            switch(error.code) {
                case error.PERMISSION_DENIED:
                    document.getElementById("location").innerHTML = "User denied the request for Geolocation.";
                    break;
                case error.POSITION_UNAVAILABLE:
                    document.getElementById("location").innerHTML = "Location information is unavailable.";
                    break;
                case error.TIMEOUT:
                    document.getElementById("location").innerHTML = "The request to get user location timed out.";
                    break;
                case error.UNKNOWN_ERROR:
                    document.getElementById("location").innerHTML = "An unknown error occurred.";
                    break;
            }
        }