Altering the location display on an HTML5 map through user selection from a dropdown menu

I'm currently working on a school project that involves coding. I've successfully implemented geolocation code to display the user's location upon page load. Now, I need to add a drop-down box that allows users to select from three additional locations - Walt Disney World, Honolulu, and Paris. To achieve this, I believe I need to use if statements in conjunction with Google Maps API for each location to change the map image displayed based on the selection made by the user. Below is a snippet of my current code:

CSS

html{ 
    height: 90% 
}
body{ 
    height: 100%; 
    margin: 0px; 
    padding: 0px; 
}
#map_canvas{ 
    height: 90%; 
    width: 90%; 
}

JS

var watchID;
var geo; // for the geolocation object
var map; // for the google map object
var mapMarker; // the google map marker object

// position options
var MAXIMUM_AGE = 200; // miliseconds
var TIMEOUT = 300000;
var HIGHACCURACY = true;

function getGeoLocation() {
    try {
        if (!!navigator.geolocation) return navigator.geolocation;
        else return undefined;
    } catch (e) {
        return undefined;
    }
}

// More JavaScript functions...

window.onload = function() {
    if ((geo = getGeoLocation())) {
        startWatching();
    } else {
        alert('Geolocation not supported.')
    }
}

HTML

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<div id="map_canvas"></div>
<section>
  <div id="vacationLocations">
    <h2>Vacation Locations</h2>
    <form name="tripSelection" method="post" method="get">
      <div class="formRow">
        <label for="serviceSelection">
          Trip Selection</label>
        <select name="tripSelection" id="tripSelection" class="validated" required>
          <option value="">-Select One-</option>
          <option value="1">Paris, France</option>
          <option value="2">Honolulu, Hawaii</option>
          <option value="3">Walt Disney World, Florida</option>
        </select>
      </div>
  </div>

This is what I have already in the program and it is working. Here is the code I have for Disney followed by the coordinates I have found for the other locations:

<!DOCTYPE html>
<html>
<head>
  <script
     src="http://maps.googleapis.com/maps/api/js">
  </script>

  <script>
  function initialize() {
      var mapProp = {
center:new google.maps.LatLng(28.3341439,-81.5871676),
zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP
    };
    var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

Coordinates: - Paris, France: 48.8589507,2.2775174 - Honolulu, Hawaii: 21.3282956,-157.9390673

Any assistance on how to implement changing the map based on the selected location would be highly appreciated.

Answer №1

I successfully programmed a solution that met my requirements. Here is the code:

<!DOCTYPE html>
<html class lang="en">

<!-- 
  geoLocMap.html by Bill Weinman 
  <http://bw.org/contact/>
  created 2011-07-07
  updated 2011-07-20

  Copyright (c) 2011 The BearHeart Group, LLC
  This file may be used for personal educational purposes as needed. 
  Use for other purposes is granted provided that this notice is
  retained and any changes made are clearly indicated as such. 
-->

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
    html { height: 90% }
    body { height: 100%; margin: 0px; padding: 0px }
    #map_canvas { height: 90%; width: 90% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
    var watchID;
    var geo;    // for the geolocation object
    var map;    // for the google map object
    var mapMarker;  // the google map marker object

    // position options
    var MAXIMUM_AGE = 200; // miliseconds
    var TIMEOUT = 300000;
    var HIGHACCURACY = true;

    function getGeoLocation() {
        try {
            if( !! navigator.geolocation ) return navigator.geolocation;
            else return undefined;
        } catch(e) {
            return undefined;
        }
    }

    function show_map(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lon);

        if(map) {
            map.panTo(latlng);
            mapMarker.setPosition(latlng);
        } else {
            var myOptions = {
                zoom: 18,
                center: latlng,

                // mapTypeID --
                // ROADMAP displays the default road map view
                // SATELLITE displays Google Earth satellite images
                // HYBRID displays a mixture of normal and satellite views
                // TERRAIN displays a physical map based on terrain information.
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            map.setTilt(0); // turns off the annoying default 45-deg view

            mapMarker = new google.maps.Marker({
                position: latlng,
                title:"You are here."
            });
            mapMarker.setMap(map);
        }
    }

    function geo_error(error) {
        stopWatching();
        switch(error.code) {
            case error.TIMEOUT:
                alert('Geolocation Timeout');
                break;
            case error.POSITION_UNAVAILABLE:
                alert('Geolocation Position unavailable');
                break;
            case error.PERMISSION_DENIED:
                alert('Geolocation Permission denied');
                break;
            default:
                alert('Geolocation returned an unknown error code: ' + error.code);
        }
    }

    function stopWatching() {
        if(watchID) geo.clearWatch(watchID);
        watchID = null;
    }

    function startWatching() {
        watchID = geo.watchPosition(show_map, geo_error, {
            enableHighAccuracy: HIGHACCURACY,
            maximumAge: MAXIMUM_AGE,
            timeout: TIMEOUT
        });
    }

    window.onload = function() {
        if((geo = getGeoLocation())) {
            startWatching();
        } else {
            alert('Geolocation not supported.')
        }
    }
</script>
<!--Changes added by Eric Wood  -->
<script>
    function tripChange() {
        var s = document.getElementById("tripSelection");
        var tripSelection = s.options[s.selectedIndex].value;

        if (tripSelection == 1) {
            value1();
        }else if(tripSelection == 2){
            value2();
        }else if(tripSelection == 3){
            value3();
        }
    }
            function value1() {
                var mapProp = {
                    center:new google.maps.LatLng(48.8589507,2.2775174),
                    zoom:14,
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                };
                var Map=new google.maps.Map(document.getElementById("map_canvas"), mapProp);
            }

            function value2() {
                var mapProp = {
                    center:new google.maps.LatLng(21.3282956,-157.9390673),
                    zoom:14,
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                };
                var Map=new google.maps.Map(document.getElementById("map_canvas"), mapProp);
            }

            function value3() {
                var mapProp = {
                    center:new google.maps.LatLng(28.3341439,-81.5871676),
                    zoom:14,
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                };
                var Map=new google.maps.Map(document.getElementById("map_canvas"), mapProp);
            }
</script>
</head>
<body>
      <div id="map_canvas"></div>
    <section>
    <div id="vacationLocations" >
        <h2>Vacation Locations</h2>
    <form name="tripSelection" method="post" method="get" >
        <div class="formRow">
            <label for="serviceSelection">
             Trip Selection</label>
            <select name="tripSelection" id="tripSelection" class="validated" onchange="tripChange()" required>
                <option value="">-Select One-</option>
                <option value="1">Paris, France</option>
                <option value="2">Honolulu, Hawaii</option>
                <option value="3">Walt Disney World, Florida</option>
            </select>
        </div>
</div>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method to initiate a page refresh from a different page without redirecting?

My website consists of numerous pages like this, each with unique GET parameters such as benchmark.php?game_id=87 which fetches game information from a database and includes an Edit button. Upon clicking the Edit button, a new window is opened using JavaS ...

Transform a 3D text rotation JavaScript file into an Angular component tailored TypeScript file

I have a javascript file that rotates text in 3D format, and I need help converting it into an Angular component specific TypeScript file. You can find the codepen for the original JavaScript code here. Below are my Angular files: index.html <!doctyp ...

Configuring the TradingView widget with NextJS Script

Struggling with transferring an article on my website from Jekyll to NextJS, I'm facing a roadblock in passing widget configuration to the built-in Script component. The widget doesn't display as it should. Below is the snippet of code causing th ...

Create a 2x2 HTML table where the first row remains undivided

I am working with an HTML table that is 2x2. Within this table, I am trying to achieve a layout where the first row consists of only one cell that spans the full width of the table, without being divided into two parts. ------- | | ------- | | | -- ...

Instructions for calculating the product of two text fields and showing the result in a separate text field without hitting submit in Rails (using jQuery or JavaScript)

Hello, I'm attempting to multiply the values of two text fields in Rails and display the result in another text field. In jQuery, we achieve this by performing a specific function. You can test it out on this link. However, I'm struggling to impl ...

Is it necessary to alert when there is a collision between a TypeScript type and a constant with the same name in a

     I am encountering an issue with my TypeScript code. Here is a snippet from Project.ts:     import type { SomeType } from '../../types/Project'; // import { SomeType } from '../../types/Project'; tried this too const SomeTyp ...

Reasons for aligning inline elements with input boxes

I am facing a challenge with aligning a series of inline elements, each containing an input text box, within a single row. The number and labels of these input boxes can vary as they are dynamically loaded via AJAX. The width of the div housing these inli ...

JQuery Form Wizard - Adding a Finish Button Linked to a Page

Having some difficulty linking the finish button on my Jquery Form Wizard within my Flask App to a link. I attempted to test the functionality by creating a simple alert, but that didn't work either. I'm certain that I missed a step somewhere, b ...

Using React to open a (.json) file through a dialog box and access the contents

I'm struggling to understand how to load a local .json file and access its contents in order to store it in a 'state' variable. Here's the code I have so far: import React, { Component } from 'react' import Files from ' ...

Troubles with modal functionality in Ionic application involving ion-slide-box

Utilizing ion-slider to display images has been a seamless experience, except for one hiccup. If I navigate directly from the first full image back to the home screen, the slider ceases to function properly. To address this challenge, I have employed spec ...

Tips for minimizing deep nesting of asynchronous functions in Node.js

I have a goal to create a webpage that showcases data fetched from a database. To achieve this, I've written functions to retrieve the necessary information from the DB using Node.js. Being relatively new to Node.js, my understanding is that to displa ...

Resetting Tabs in Child Component using React

Imagine having two intricate React components developed in TypeScript where one acts as a child component of the other. This child component consists of tabs and keeps track of its own state to determine which tab is currently selected: export const Clien ...

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: https://i.sstatic.net/C81tg.png The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there ma ...

What is causing the scrollbars to appear only in IE on this layout?

While my layout functions properly in Chrome, I am encountering an issue in IE where the main content area is displaying scrollbars instead of filling out 100% as intended. Is there a way to fix this? In the design I am working on, the main content area h ...

Generating interactive elements in VUE is key

I am unsure about how to dynamically create components without using the <component :is=''> tag. I would like to insert a component into the DOM through JavaScript. Similar to how you would add a new modal in jQuery with $("body").append(" ...

Explore relevant Pill information dynamically based on the image that was clicked in Angular

In this particular situation: Using Angular 1.7.2 Utilizing Bootstrap 3 Encountering some challenges after the user interacts with the image: Current Behavior: Upon clicking any image, a modal window appears displaying relevant content. If image 1 is ...

Issue with triggering e.preventDefault() on multiple dynamic forms

I'm working on a PHP page where multiple forms (checkboxes) are being generated and I need to update the database when they are toggled, all without reloading the page. Each form has a shared class (prim) and unique id (primary1, primary2, etc). Even ...

Angular encountered a 405 error when trying to execute a GET request due to the method

Having trouble with implementing a new function in my application (built with angular). When I call an API (built with Lumen), it returns a 405 error when tested locally and "XMLHttpRequest cannot load Response for preflight is invalid (redirect)" when tes ...

Incorporating Local Storage into a To-Do List Application

I followed a tutorial from w3schools to create a custom task list, tweaking the code to fit my requirements. My goal is to ensure that when I click the save button in the toolbar at the top and then refresh the page, the added tasks are preserved. I&apos ...

What is the process of resetting dropdown option values?

Recently, I have encountered an issue with a customized dropdown list in MVC4. I am populating data using AJAX and it is working fine, but the problem arises when the data is not cleared after successfully sending it to the controller. Here's an examp ...