Josh Winters
Josh Winters

Reputation: 855

How to access arcgis map via components?

The code below is taken directly from arcgis via react on how to display a map.

If i wanted to say, zoom in to a set of coordinates, but the code for that was set in another component, how can i get that component to talk to the map here in this component?

import Map from '@arcgis/core/Map';
import MapView from '@arcgis/core/views/MapView';

const map = new Map({
  basemap: "topo-vector"
});

const view = new MapView({
  container: "viewDiv",
  map: map
});

Upvotes: 3

Views: 533

Answers (3)

Josh Winters
Josh Winters

Reputation: 855

I resolved this by using redux toolkit to set the map as a global state object.

  1. The entire map view is set in a useEffect, once i initialize each of the views, i dispatch the map view to a reducer in rtk.
    dispatch(updateMapViewState(view));

    updateMapViewState: (state, action) => {
      state.view = action.payload
    },

Then, when i want to use the map in a separate component, i do:

    const view = useSelector((state) => state.MapSlice.view);

In this way, all components can access the map outside of the useEffect in the map component, and can manipulate it without creating a new map view. This worked for me. I assume you could probably do this with context api, but we aren't using that as a global state manager.

Upvotes: 1

eKerney
eKerney

Reputation: 21

Still looking for a clear answer to this problem. Have not found an example separating the map/view creation and adding layers into differing components.

Upvotes: 0

Stephen Lead
Stephen Lead

Reputation: 1976

This may not be the recommended or best way to achieve this, but I had success by passing the view object from the map component back to the parent component, then saving it to the parent component's state.

// in App.js
saveViewToState(view){
  this.setState({view: view})
}

<MapComponent saveViewToState={this.saveViewToState}/>

// in MapComponent.js
let view = new View()
this.props.saveViewToState(view)

Then I was able to interact with the view object from the parent:

// in App.js
this.state.view.extent = {xmin: 1, ymin: 1, xmax: 2, ymax: 2}

This doesn't work perfectly (for some reason I can't call view.goTo, but view.extent works). I'd be keen to hear if there is a better way to achieve this.

Upvotes: 0

Related Questions