Home > Back-end >  react leaflet -layer control -satellite view
react leaflet -layer control -satellite view

Time:10-15

I want to use the leaflet map on my react project and I would like to add a layer control where the user can switch between street view and satellite view. I am trying to use google satellite view, but it doesn't seem to work.

Here is my code

function App() {
  
  return (
    <div className="App">
      <MapContainer center={[40.44695, -345.23437]} zoom={2}>
        <LayersControl>
          <BaseLayer checked name="OpenStreetMap">
            <TileLayer
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            />
          </BaseLayer>

          <BaseLayer name="Satellite View">
            <TileLayer
                url='https://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}'
                maxZoom= {20}
              />
            
          </BaseLayer>
        </LayersControl>
      </MapContainer>
    </div>
  );
}

export default App;

Satellite View

Thank you very much

CodePudding user response:

The tile url you are using for Google maps does not exist:

https://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}

From the Leaflet docs:

{s} means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; a, b or c by default, can be omitted), {z} — zoom level, {x} and {y} — tile coordinates. {r} can be used to add "@2x" to the URL to load retina tiles.

The urls you are requesting are using the default subdomains a, b and c which all appear broken:

It looks like the correct subdomains are mt1, mt2 and mt3. You can specify them using the subdomains prop:

<TileLayer
   url='https://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}'
   maxZoom= {20}
   subdomains={['mt1','mt2','mt3']}
/>

https://mt1.google.com/vt/lyrs=s&x=1&y=1&z=1

  • Related