Shashwat Shrivastava
Shashwat Shrivastava

Reputation: 19

The Map is not showing the correct location using Geocoder. It points to the default coordinates

This code is not giving a zoomed marker at correct location. It stays at the default position instead of address received, even though the original source code works for others. There are no terminal or console errors.

GeoCoderMarker.jsx :

import React, { useEffect, useState } from 'react'
import { Marker, Popup, useMap } from 'react-leaflet'
import L from 'leaflet'
import "leaflet/dist/leaflet.css"
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";
import * as ELG from 'esri-leaflet-geocoder'

let DefaulIcon = L.icon ({
    iconUrl : icon, 
    shadowUrl: iconShadow
})
L.Marker.prototype.options.icon = DefaulIcon


const GeoCoderMarker = ({address}) => {

    const map = useMap()
    const [position, setPosition] = useState([60, 19])

    useEffect(()=> {
        ELG.geocode().text(address).run((err, results, response)=> {
            if(results?.results?.length > 0){
                const {lat, lng} = results?.results[0].latlng
                setPosition([lat, lng])
                map.flyTo([lat, lng], 6)
            }
        })
    }, [address])

  return (
    <Marker position={position} icon={DefaulIcon}>
        <Popup/>
    </Marker>
  )
}

export default GeoCoderMarker

Map.jsx :

import React from 'react'
import {MapContainer, TileLayer} from 'react-leaflet'
import GeoCoderMarker from '../GeoCoderMarker/GeoCoderMarker'
const Map = ({address, city, country}) => {
  return (
    <MapContainer
    center={[53.35, 18.8]}
    zoom={1}
    scrollWheelZoom={false}
    style={{
        height: "40vh",
        width: "100%",
        marginTop: "20px",
        zIndex: 0,
       
    }}
    >
        <TileLayer url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'/>
        <GeoCoderMarker address={`${address} ${city} ${country}`} />
    </MapContainer>
  )
}
export default Map

Upvotes: 1

Views: 49

Answers (1)

voidbrain
voidbrain

Reputation: 362

Put an else on if(results?.results?.length > 0){

Upvotes: 0

Related Questions