如何在 react-google-maps 中设置起点

How to set start point in react-google-maps

我正在开发我正在使用的应用程序react-google-maps,我在应用程序中集成了多个停止功能。现在我想设置它的起点,例如,我想从它的起点绘制多个停靠点,它必须是一个带有文本的标记(开始)。我真的试过但没能解决这个解决方案,我也会附上我想要实现的图像。

代码

import React, { useState } from "react";
import {
  GoogleMap,
  InfoWindow,
  Marker,
  Polyline,
} from "@react-google-maps/api";

function Map({ scheduledOrders }) {
  const [activeMarker, setActiveMarker] = useState(null);

  let markers =
    scheduledOrders !== undefined &&
    scheduledOrders &&
    scheduledOrders[0] &&
    scheduledOrders[0].map((item, index) => ({
      id: index + 1,
      name: item.customerName + " - " + item.customerAddress,
      position: {
        lat: Number(item && item.order_lat, 10),
        lng: Number(item && item.order_lng, 10),
      },
    }));


  console.log("@@@markser", markers);

  const handleActiveMarker = (marker) => {
    if (marker === activeMarker) {
      return;
    }
    setActiveMarker(marker);
  };

  const handleOnLoad = (map) => {
    const bounds = new window.google.maps.LatLngBounds();
    markers && markers.forEach(({ position }) => bounds.extend(position));
    map.fitBounds(bounds);
  };

  return (
    <GoogleMap
      onLoad={handleOnLoad}
      onClick={() => setActiveMarker(null)}
      mapContainerStyle={{ width: "100%", height: "88vh" }}
    >
      <Polyline
        path={
          scheduledOrders !== undefined &&
          scheduledOrders &&
          scheduledOrders[0] &&
          scheduledOrders[0].map((item) => ({
            lat: Number(item && item.order_lat, 10),
            lng: Number(item && item.order_lng, 10),
          }))
        }
        options={{
          strokeColor: "#07966B",
          strokeOpacity: 1,
          strokeWeight: 2,
          icons: [
            {
              icon: "hello",
              offset: "0",
              repeat: "10px",
            },
          ],
        }}
      />
      {markers &&
        markers.map(({ id, name, position }) => (
          <Marker
            key={id}
            position={position}
            onClick={() => handleActiveMarker(id)}
            label={{ text: `${id}`, color: "white" }}
          >
            {activeMarker === id ? (
              <InfoWindow onCloseClick={() => setActiveMarker(null)}>
                <div>{name}</div>
              </InfoWindow>
            ) : null}
          </Marker>
        ))}
    </GoogleMap>
  );
}

export default Map;

您的代码对于多段线的起点和终点路径似乎具有相同的坐标。为了实现您的用例,我有两种方法可以解决这个问题。

这是第一个,您需要先获取起点的坐标并将其放在单独的 variable.Then 中,您需要为此坐标创建一个单独的 <Marker> 对象,条件是它将检查起始坐标变量是否具有值。这将创建一个您可以自定义的单独的标记对象。 接下来,您只需要在 markers 变量中映射所有中间(航路点)坐标。

这是我制作的 sample code 和代码片段。我刚刚从 json 文件传递​​了 scheduledOrders 值。

import React, { useState } from "react";
import {
  GoogleMap,
  InfoWindow,
  Marker,
  Polyline
} from "@react-google-maps/api";

import scheduledOrders from "./data.json";

function Map() {
  const [activeMarker, setActiveMarker] = useState(null);
  let startMarker = null;
  let wayptMarker = [];

//get the first point and put it in a startMarker variable then put the middle points in an array(wayptMarker)
  scheduledOrders.map((item, index, arr) => {
    if (index == 0 || index == arr.length - 1) {
      //Since the start and end point are the same, I only get the start point details in my startMarker variable
      if (index == 0) {
        startMarker = item;
      }
    } else {
      wayptMarker.push(item);
    }
  });

//put your startposition here
  let startPosition = {
    lat: startMarker.order_lat,
    lng: startMarker.order_lng
  };
//put your start name here
  let startName =
    startMarker.customerName + " - " + startMarker.customerAddress;


  let markers =
    scheduledOrders !== undefined &&
    scheduledOrders &&
    wayptMarker.map((item, index) => ({
      id: index + 1,
      name: item.customerName + " - " + item.customerAddress,
      position: {
        lat: Number(item && item.order_lat, 10),
        lng: Number(item && item.order_lng, 10)
      }
    }));


  console.log("@@@markser", scheduledOrders);

  const handleActiveMarker = marker => {
    if (marker === activeMarker) {
      return;
    }
    setActiveMarker(marker);
  };

  const handleOnLoad = map => {
    const bounds = new window.google.maps.LatLngBounds();
    markers && markers.forEach(({ position }) => bounds.extend(position));
    map.fitBounds(bounds);
  };

  return (
    <GoogleMap
      onLoad={handleOnLoad}
      onClick={() => setActiveMarker(null)}
      mapContainerStyle={{ width: "100%", height: "88vh" }}
    >
      <Polyline
        path={
          scheduledOrders !== undefined &&
          scheduledOrders &&
          scheduledOrders[0] &&
          scheduledOrders.map(item => ({
            lat: Number(item && item.order_lat, 10),
            lng: Number(item && item.order_lng, 10)
          }))
        }
        options={{
          strokeColor: "#07966B",
          strokeOpacity: 1,
          strokeWeight: 2,
          icons: [
            {
              icon: "hello",
              offset: "0",
              repeat: "10px"
            }
          ]
        }}
      />
     {/* I created a marker solely for startMArker where you can customize the  icon for this only marker */}
      {startMarker != null && (
        <Marker
          key="start"
          position={startPosition}
          onClick={() => handleActiveMarker("start")}
          label={{ text: `START`, color: "black" }}
          icon="http://maps.google.com/mapfiles/kml/shapes/arrow.png"
        >
          {activeMarker === "start" ? (
            <InfoWindow onCloseClick={() => setActiveMarker(null)}>
              <div>{startName}</div>
            </InfoWindow>
          ) : null}
        </Marker>
      )}
  {/* The following Marker object will only create markers for the middle points */}
      {markers &&
        markers.map(({ id, name, position }) => (
          <Marker
            key={id}
            position={position}
            onClick={() => handleActiveMarker(id)}
            label={{ text: `${id}`, color: "white" }}
          >
            {activeMarker === id ? (
              <InfoWindow onCloseClick={() => setActiveMarker(null)}>
                <div>{name}</div>
              </InfoWindow>
            ) : null}
          </Marker>
        ))}
    </GoogleMap>
  );
}

export default Map;

第二种方法是简单地将条件放入您的 <Marker> 对象中,该对象将检查您正在映射的 markers 是第一个还是最后一个,然后它将显示 <Marker> 对象作为开始,如果不是,另一个 <Marker> 对象将显示您的 waypoints.

下面是 sample code 和代码片段:

import React, { useState } from "react";
import {
  GoogleMap,
  InfoWindow,
  Marker,
  Polyline
} from "@react-google-maps/api";

import scheduledOrders from "./data.json";

function Map() {
  const [activeMarker, setActiveMarker] = useState(null);

  let markers =
    scheduledOrders !== undefined &&
    scheduledOrders &&
    scheduledOrders.map((item, index) => ({
      id: index + 1,
      name: item.customerName + " - " + item.customerAddress,
      position: {
        lat: Number(item && item.order_lat, 10),
        lng: Number(item && item.order_lng, 10)
      }
    }));

  console.log("@@@markser", scheduledOrders);

  const handleActiveMarker = marker => {
    if (marker === activeMarker) {
      return;
    }
    setActiveMarker(marker);
  };

  const handleOnLoad = map => {
    const bounds = new window.google.maps.LatLngBounds();
    markers && markers.forEach(({ position }) => bounds.extend(position));
    map.fitBounds(bounds);
  };

  return (
    <GoogleMap
      onLoad={handleOnLoad}
      onClick={() => setActiveMarker(null)}
      mapContainerStyle={{ width: "100%", height: "88vh" }}
    >
      <Polyline
        path={
          scheduledOrders !== undefined &&
          scheduledOrders &&
          scheduledOrders[0] &&
          scheduledOrders.map(item => ({
            lat: Number(item && item.order_lat, 10),
            lng: Number(item && item.order_lng, 10)
          }))
        }
        options={{
          strokeColor: "#07966B",
          strokeOpacity: 1,
          strokeWeight: 2,
          icons: [
            {
              icon: "hello",
              offset: "0",
              repeat: "10px"
            }
          ]
        }}
      />

      {/* The following Marker object will check if the index is the start or end */}
      {markers &&
        markers.map(({ id, name, position }, i, arr) => {
          if (i == 0 || i == arr.length)
            return (
              <Marker
                key="start"
                position={position}
                onClick={() => handleActiveMarker("start")}
                label={{ text: `START`, color: "black" }}
                icon="http://maps.google.com/mapfiles/kml/shapes/arrow.png"
              >
                {activeMarker === "start" ? (
                  <InfoWindow onCloseClick={() => setActiveMarker(null)}>
                    <div>This is the start</div>
                  </InfoWindow>
                ) : null}
              </Marker>
            );
          return (
            <Marker
              key={id}
              position={position}
              onClick={() => handleActiveMarker(id)}
              label={{ text: `${id - 1}`, color: "white" }}
            >
              {activeMarker === id ? (
                <InfoWindow onCloseClick={() => setActiveMarker(null)}>
                  <div>{name}</div>
                </InfoWindow>
              ) : null}
            </Marker>
          );
        })}
    </GoogleMap>
  );
}

export default Map;