Entering destinations into the Google Maps search bar

I am currently working on a project that involves creating a Google Maps window. The goal is for the user to input their location (marker A) and receive directions to a specified destination (marker B), ideally using an input box and submit button. So far, I have declared location A in the code and it cannot be moved within the window. However, I am struggling to create the input box successfully. If anyone can offer assistance with this task, it would be greatly appreciated.

Here is the code snippet I have developed:

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Directions Example</title>
<script type="text/javascript"
       src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 600px;">
 <div id="map" style="width: 280px; height: 400px; float: left;"></div>
 <div id="panel" style="width: 300px; float: right;"></div>
</div>

<script type="text/javascript">

 var directionsService = new google.maps.DirectionsService();
 var directionsDisplay = new google.maps.DirectionsRenderer();

 var map = new google.maps.Map(document.getElementById('map'), {
   zoom:7,
   mapTypeId: google.maps.MapTypeId.ROADMAP
 });

 directionsDisplay.setMap(map);
 directionsDisplay.setPanel(document.getElementById('panel'));

 var request = {
   origin: 'Dublin',
   destination: '53.4198282,-6.2183937',
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };

  directionsService.route(request, function(response, status) {
   if (status == google.maps.DirectionsStatus.OK) {
     directionsDisplay.setDirections(response);
   }
 });
 </script>
 </body>
 </html>

The current output can be viewed here: https://i.sstatic.net/R80oB.png

If you have any insights or suggestions on how to improve the input box functionality, please share them. Thank you!

Answer №1

To capture the value of an input field when a user enters it and use it as the 'origin', you should avoid hardcoding strings.

Here is a simple example to help you get started:

HTML:

<div class="address-form">
    Enter your address: <input id="address" type="text" />
    <input id="submit" type="submit" />
</div>

JS:

$('#submit').click(function() {
    var address = $('#address').val();
    var request = {
        origin: address,
        destination: '53.4198282,-6.2183937',
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
});

JSFiddle

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

Differences in browser behavior can cause varying outcomes in the Web API URL

I am currently utilizing jQuery to make Web API calls on my website. Surprisingly, it works perfectly fine when tested in Chrome However, testing it in IE 11 results in a frustrating 404 error An observation I've made is that IE 11 includes the s ...

Managing user logins across different sessions using passport.js, mysql database, and express-session

Currently, my app utilizes Passport.js for user authentication with Facebook, which is functioning properly. The issue arises when my node.js server is restarted and the users are automatically logged out. It appears that using express-sessions would be a ...

How can I display SQL results in a Jade page using Node, Express, and MySQL?

My application built with Node.js and Express is connected to a MySQL database for monitoring purposes. The code structure is as follows: In the Node file: app.get('/banners', function(req,res){ connection.query("SELECT * FROM banner_store_ ...

Fetching data from a Django view using a JavaScript AJAX POST call

Utilizing Javascript for an asynchronous request to a Django View, I am able to successfully receive data from the POST request. However, I am encountering issues with returning a confirmation message that the process was successful. Despite expecting xhtt ...

Deletion of input is not permitted

Currently, I have a telephone input field on my form that only allows numbers. I have implemented a simple JavaScript code to enforce this validation. However, the issue I am facing now is that the input box cannot be deleted. <form id="aylikal" action ...

The JavaScript Date() string that was inserted into the database is now elegantly displayed

Can you help me figure out how to format a date string that's stored in a database like this: 2016-09-13T18:18:08.518Z, into a more visually appealing format such as: 13 September 2016? Thank you in advance! ...

What is the correct way to remove listeners in componentWillUnmount using React, and why is binding necessary in the constructor?

I'm feeling a bit perplexed, can someone explain the distinction between these two snippets of code: constructor(props) { super(props); this.state = { openPane: false } this.togglePaneHelper = this.togglePaneHelper.bind(this); ...

What is the reason that the values in the select option only appear once it has been clicked on?

After loading or reloading the page, I am experiencing an issue where the select options do not appear on the first click and the values are not displayed until the second click. Any assistance would be greatly appreciated! I am still new to coding, so ple ...

Retrieve the child elements belonging to a specific type of element

My challenge involves a table identified by the id of tableDiv. I am looking to dynamically reset the values of each table header and data cells, but due to the nature of the table being created with ASP.NET (GridView), I am unable to assign classes for th ...

Achieve equal heights and vertical alignment for Bootstrap 4 accordion header with floated left and right divs

Building a Bootstrap 4 accordion, I encountered an issue. In the button header, I have two divs with one floating left and the other floating right. The right div contains an image, while the left div contains a title and a subtitle. Everything works perf ...

The module 'PublicModule' was declared unexpectedly within the 'AppModule' in the Angular 4 component structure

My goal is to create a simple structure: app --_layout --public-footer ----public-footer.html/ts/css files --public-header ----public-header.html/ts/css files --public-layout ----public-layout.html/ts/css files In public-layout.html, the stru ...

JQGrid is a unique event grid that triggers only once for the inaugural loading, allowing users to apply a default filter upon first loading

I am currently using JQGrid (jQuery jQgrid not Gurrido) version 4.6.0 and I am in need of an event that occurs only once the grid has completed loading for the first time. I have attempted to use loadComplete and gridComplete, but it seems they both perfor ...

Utilize the Jquery UI feature by seamlessly dragging and dropping items onto tables

I'm currently working on implementing a drag and drop feature that involves moving items from table1 to table2. My goal is to ensure that when the user drags an item from table1, the cell in table2 where it is dropped remains empty. If the cell in tab ...

Making an API request using jQuery

I am currently working on creating a .js file that will send data to an external API, wait for a response, and then interpret the results. The external API I am using is XML-based and requires an HTTPS Post request with the XML content in the body (content ...

Create numerous collapsible elements using the ui.bootstrap and AngularJS frameworks

Currently, I am working on implementing the ui bootstrap collapse feature. The static single or double collapse system works perfectly fine, but for my specific design requirements, I need to create collapses using ng-repeat. Unfortunately, I am unsure how ...

Encountering a SonarQube error message stating "Unnecessary 'undefined' should be removed" when using "undefined" as a function argument

When calling a function, I have been passing "undefined" multiple times as a parameter. However, the SonarQube report is flagging an error stating "Remove this redundant undefined". https://i.stack.imgur.com/YhOZW.png It should be noted that the function ...

Changing a JavaScript string into an array

I have extracted an array of objects from a hidden HTML input field and received the following string: "{"id":"1234","name":"john smith","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab0a9b7b3aeb29ab8b6bbb2f4b9b5b7" ...

Unexpectedly, CSS is failing to override React-Bootstrap and Bootstrap as intended

Currently, I am tackling a project that involves utilizing react-bootstrap along with my own custom CSS for styling. Both are imported in my index.js file as shown below: import React from 'react'; import ReactDOM from 'react-dom'; impo ...

When employing a CSS combination of `position: fixed;` and `display: flex;`, the upper portion of the inner element is excised and out of reach

I'm currently working on a fullscreen modal and facing an issue with centering the content vertically when it is smaller than the screen. Additionally, I need the content to start at the top and allow scrolling when its height exceeds the container&ap ...

Designating the selected button as "active"

Consider the following HTML snippet: <div class="wp-editor-tabs"><button type="button" id="bbp_topic_content-tmce" class="wp-switch-editor switch-tmce" data-wp-editor-id="bbp_topic_content">Visual</button> <button type="button" id="bb ...