How do you utilize the google maps elevation service as a jsx tag?

726 views Asked by At

I have been developing a customized google map, and a feature that I need is to be able to tell about the elevation of different locations on click. I have coded the map with a bunch of jsx tags (i.e a tag for google map, a tag for marker, etc...). However, I have not been able to figure out how to do this for the elevation service. So my question is, is it possible to use the google map elevation service as a jsx tag, and if so, what is the import? If not, what are some alternatives to adding this feature?

1

There are 1 answers

0
Pagemag On

You can check first the Elevation Service of Google Maps Platform.

You can also check how I implemented it in a reactjs code in this working sample and code snippet below:

import React, { Component } from "react";
import { render } from "react-dom";
import Map from "./Map";
import "./style.css";

class App extends Component {
  render() {
    return (
      <Map
        id="myMap"
        options={{
          center: { lat: 41.0082, lng: 28.9784 },
          zoom: 8,
          mapTypeId: "terrain"
        }}
        onMapLoad={map => {
          const elevator = new google.maps.ElevationService();
          const infowindow = new google.maps.InfoWindow({});
          infowindow.open(map);
          // Add a listener for the click event. Display the elevation for the LatLng of
          // the click inside the infowindow.
          map.addListener("click", event => {
            displayLocationElevation(event.latLng, elevator, infowindow);
          });

          function displayLocationElevation(location, elevator, infowindow) {
            // Initiate the location request
            elevator.getElevationForLocations(
              {
                locations: [location]
              },
              (results, status) => {
                infowindow.setPosition(location);

                if (status === "OK") {
                  // Retrieve the first result
                  if (results[0]) {
                    // Open the infowindow indicating the elevation at the clicked position.
                    infowindow.setContent(
                      "The elevation at this point <br>is " +
                        results[0].elevation +
                        " meters."
                    );
                  } else {
                    infowindow.setContent("No results found");
                  }
                } else {
                  infowindow.setContent(
                    "Elevation service failed due to: " + status
                  );
                }
              }
            );
          }
        }}
      />
    );
  }
}

export default App;