2

I am junior front end working on a project in react where you can post job offers with information and google map location. Project screenshot

How the component works?

When I click on the <GoogleMap/> component, an alert show with "www...want to know your location, allow/deny". After allowing or denying my location I need to click again on the map to open google map in a new tab.

How the component should work?

When I click on the <GoogleMap/> component, an alert should show with "www...want to know your location, allow/deny" and after allowing or denying my location google maps should open in a new tab without need to click again on <GoogleMap/> component.

Code sample:

  const [start, setStart] = useState(false)

  const getBrowserLocation = () => {
    if (!navigator.geolocation) return;
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        setCurrentLocation({ lat: latitude, lng: longitude });
      },
      (error) => {
        console.log(error);
      }
    )
  };


  const openMapWithCurrentLocation = () => {
    if (start === false) {
      getBrowserLocation();
      setStart(true)
    }
    if (currentLocation && start) {
      return window.open(`https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}&travelmode=driving&origin=${currentLocation.lat},${currentLocation.lng}`, '_blank')
    } else if (start) {
      return window.open(`https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}&travelmode=driving`, '_blank')
    }

  }


  if (!isLoaded || !latitude || !longitude) {
    return <></>;
  }

  return (
    <div className={styles["map__container"]}>
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={center}
        onLoad={handleLoadMap}
        onUnmount={onUnmount}
        onClick={openMapWithCurrentLocation}
      >
        <Marker
          position={center}
          onClick={openMapWithCurrentLocation}
        />
      </GoogleMap>
    </div>
  )
}

export default MapMarker;

I have changed the code a little bit just to be able to run it in codesandbox: https://codesandbox.io/embed/frosty-fog-xbccr4?fontsize=14&hidenavigation=1&theme=dark

bigBadWolf
  • 100
  • 1
  • 9

1 Answers1

1
const getLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  }
}

const showPosition = (position) => {
   // Your Code
   console.log(position.coords.latitude);
   console.log(position.coords.longitude);
}

<button onClick="getLocation()">Get Location</button>
Areg Nikoghosyan
  • 449
  • 5
  • 14