1

Using the google-map-react package, I've created a MapView component in TypeScript as follows.

export function MapView<I extends Mappable>({ getData }: MapViewProps<I>): JSX.Element {
  const [mapZoom, setMapZoom] = useState(5);
  const [mapBounds, setMapBounds] = useState<[number, number, number, number]>([-1, -1, -1, -1]);

  return (
    <div className="map-container">
      <GoogleMapReact
        bootstrapURLKeys={{ key: "API_KEY" }}
        defaultCenter={{
          lat: 39.381266,
          lng: -97.922211,
        }}
        zoom={mapZoom}
        options={{ maxZoom: 10 }}
        onChange={({ zoom, bounds }) => {
          setMapZoom(zoom);
          setMapBounds([bounds.nw.lng, bounds.se.lat, bounds.se.lng, bounds.nw.lat]);
        }}
      />
    </div>
  );
}

I want to make the map slowly scroll horizontally if the user has not yet touched the map. My first thought was to add a useEffect that automatically updates the bounds, but that doesn't seem ideal. Any thoughts?

jonchaf
  • 156
  • 5
  • 16

1 Answers1

0

On map load, you can put a function where the center of the map is changing for each second. You can use the Maps JavaScript Geometry Library's compute offset to get the coordinate from a specified distance in 90 degree heading to make it look like it is scrolling horizontally to the right. You can change the value of the heading to make get the center from different direction you want. You also need to make sure that the distance you set is inside the current map bounds of your current zoom level. Here is a sample code I made without using react libraries. Please use your API key for the sample to work.

Code snippet:

class App extends Component {
  render() {
    return (
      <Map
        id="myMap"
        options={{
          center: { lat: 41.0082, lng: 28.9784 },
          zoom: 5
        }}
        onMapLoad={map => {
          setInterval(function() {
            let currentCenter = map.getCenter();
            let spherical = google.maps.geometry.spherical;
            let newLat = spherical.computeOffset(currentCenter, 500000, 90);
            let newCenter= new google.maps.LatLng(newLat.lat(), newLat.lng());
            map.setCenter(newCenter);
          }, 1000);
        }}
      />
    );
  }
}
Pagemag
  • 2,779
  • 1
  • 7
  • 17