Interactive map navigation feature using React.js

Can someone help me figure out how to create a dynamic map with directions/routes? I am currently using the Directions Renderer plugin, but it only shows a static example. I want to generate a route based on user input.

Below is the code snippet:

     /* global google */
       import { default as React, Component,} from "react";
       import { withGoogleMap, GoogleMap, DirectionsRenderer,} from "../../../lib";

const DirectionsExampleGoogleMap = withGoogleMap(props => (
  <GoogleMap
    defaultZoom={7}
    defaultCenter={props.center}
  >
    {props.directions && <DirectionsRenderer directions={props.directions} />}
  </GoogleMap>
));

export default class DirectionsExample extends Component {

 constructor(props) {
    super(props);
    this.state = {
        origin: '',
        destination: '',
    }

    this.handleOrigin = this.handleOrigin.bind(this);
    this.handleDestination = this.handleDestination.bind(this);
}

handleOrigin(event) {
        event.preventDefault()
        this.setState({origin: event.target.value});
    }

handleDestination(event) {
    event.preventDefault()
    this.setState({destination: event.target.value});
}

  componentDidMount() {
    const DirectionsService = new google.maps.DirectionsService();

    DirectionsService.route({
      origin: new google.maps.LatLng(this.state.origin),
      destination: new google.maps.LatLng(this.state.destination),
      travelMode: google.maps.TravelMode.DRIVING,
    }, (result, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        this.setState({
          directions: result,
        });
      } else {
        console.error(`error fetching directions ${result}`);
      }
    });
  }

  render() {
    return (
      <input type='text' value={this.state.origin} onChange=
         {this.handleOrigin} />
      <input type='text' value={this.state.destination} onChange2=
         {this.handleDestination}/>
      <DirectionsExampleGoogleMap
        containerElement={
          <div style={{ height: `100%` }} />
        }
        mapElement={
          <div style={{ height: `100%` }} />
        }
        center={this.state.origin}
        directions={this.state.directions}
      />
    );
  }
}

Answer №1

In my experience with resolving similar issues, I have found that the following code snippets are quite useful:

    import PlacesAutocomplete from 'react-places-autocomplete';
    import { geocodeByAddress, geocodeByPlaceId } from 'react-places 
    autocomplete';

These lines of code help create a user-friendly autocomplete field. Additionally, I make use of the npm packages below to showcase maps effectively.

    import Map, {GoogleApiWrapper} from 'google-maps-react'
    import Marker from 'google-maps-react'

If you need assistance in implementing these tools or would like to see some examples, feel free to reach out. I'm here to help and provide guidance. Cheers!

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

Retrieve a list of all file names within a designated directory using Angular

I am working on my Angular app and I need to list all the file names inside the assets folder. To achieve this, I am planning to utilize the npm library called list-files-in-dir https://www.npmjs.com/package/list-files-in-dir Here is the service impleme ...

Implementing a PHP button update functionality sans utilizing an HTML form

I need a way to update my database with just a click of a button, without using any forms or POST requests. Most examples I've seen involve updating through forms and the $_POST method. Is there a simpler way to update the database by directly click ...

Accessing the constants and state of child components within a parent component in React

I've created a MUI TAB component that looks like this <Box sx={{ width: "100%" }}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label ...

When AJAX is invoked, the HTML content fails to display within a div

The following is the ajax script I am currently utilizing: mypage.php $(".sales_anchor").click(function(e) { e.preventDefault(); var store_username = $("#storeUsername").val(); var store_id = $("#storeID").val(); var sale_id = $(this).a ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

Obtaining the client's IP address using socket.io 2.0.3: a comprehensive guide

Currently, I am facing a challenge using socket.io v2.0.3 in my node.js server as I am unable to retrieve the client's IP address. Although there are several suggestions and techniques on platforms like stackoverflow, most of them are outdated and no ...

Using AngularJS to create a form and showcase JSON information

My code is below: PizzaStore.html: <!DOCTYPE html> <html ng-app="PizzaApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Delicious pizza for all!</title> ...

Determine the Size of an Image File on Internet Explorer

Is there an alternative method? How can I retrieve file size without relying on ActiveX in JavaScript? I have implemented an image uploading feature with a maximum limit of 1 GB in my script. To determine the size of the uploaded image file using Java ...

Tips for concurrently and asynchronously executing multiple AJAX requests

I am working with a javascript object named Agendamento which includes the following key parts: const Agendamento = { // ... storeResultados: async function (consulta) { //... $.ajax({ type: 'POST', ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

Sharing the checkbox's checked status with an AJAX script

I am faced with a challenge involving a table that contains checkboxes in the first column. When a checkbox is checked, it triggers an AJAX script that updates a PHP session variable with the selected values. The functionality is currently operational, but ...

Using vue-select: In VueJs, how to pass an option slot from a grandparent component

Utilizing a custom dropdown component called 'vue-select', there is an option to customize the options view using slots as detailed in this documentation -> https://vue-select.org/guide/slots.html I am aiming to achieve a similar customization b ...

Who is the intended audience for the "engines" field in an npm package - consumers or developers?

As the creator of an npm library, I have included the current LTS versions of Node.js and npm in the package manifest under the engines field. This ensures that all contributors use the same versions I utilized for development: Node.js <a href="/cdn-cgi ...

Tips for sharing data between routes in Next.js App router

Currently using App router and in need to transfer parameters as an object without reliance on useParams & useSearchParams Suppose there is an object named person const person: Person = { name: "John Doe", age: 25, address: "123 M ...

Guide to accessing and updating data in various tabs within a Google spreadsheet

I have two tabs named TAB A and TAB B. My goal is to iterate through TAB A and extract a set of values that I can then paste into TAB B. However, I encountered an error message saying, "Cannot read property 1, etc" function getValuesFromModal(form) { ...

The default theme has not been specified in Tailwind CSS

During my recent project, I utilized React, Next.js in combination with Tailwind CSS. In this project, I delved into styling customization by implementing react-slick for a specialized slider. To achieve the desired aesthetic, I made modifications to the r ...

Execute the dynamic key API function

Below is the data object: registration: { step1: { project: '', }, step2: { adres: '', facade: '', floor: '', }, }, An attempt is being ...

Can you tell me the CSS equivalent of the SASS/SCSS expression "&$"?

Hey there! I've been diving into the world of Material-UI components and stumbled upon this interesting styling snippet: root: (0, _extends3.default)({}, theme.typography.subheading, { height: theme.spacing.unit * 3, boxSizing: 'content- ...

Is there a way to invoke a class method from the HTML that is specified within its constructor function?

class Welcome { constructor() { this.handlePress = this.handlePress.bind(this); this.htmlContent = `<a onclick="this.handlePress">Link</a>`; } handlePress(e) { console.log('planet'); } } The HTML structure appears ...

Challenge with the revalidateTag() function in Next.js app routing and Sanity integration

I have been struggling to integrate the next app router with Sanity and revalidateTag() function. It has been a challenging journey as I tried to make it work for five full days across multiple projects. Here is what I have discovered so far: Project 1: T ...