Skip to content Skip to sidebar Skip to footer

Google-Map-React - Javascript: How To Click On A Customized Marker

I have a google-map with customized markers. Those markers are logos of companies. After inquiring the APIs I am able to obtain a json file with the vessels I am interested in and

Solution 1:

To make a custom marker clickable, Ship component could be extended like this:

const Ship = ({ ship }) => {
    const shipName = ship.NAME;
    const company = shipCompanyMap[shipName];

    function handleMarkerClick(){
       console.log('marker clicked');
    }

    const shipImage = companyImageMap[company];
    return (
        <div onClick={handleMarkerClick}>
            {/* Render shipImage image */}
            <img src={shipImage} alt="Logo" />
        </div>
    );
};

Here is an example which demonstrates how to make marker clickable for google-map-react library:

import React, { Component } from "react";
import GoogleMapReact from "google-map-react";
import icon from "./orange-blank.png";

const googleAPIKey = "";

const markerStyle = {
  position: "absolute"
};

function CustomMarker({lat,lng,onMarkerClick}) {
  return (
    <div onClick={onMarkerClick} lat={lat} lng={lng}>
      <img style={markerStyle} src={icon} alt="icon" />
    </div>
  );
}

function MapExample({ center, zoom, data }) {

  function handleMarkerClick(){
    console.log('Click')
  }


  return (
    <GoogleMapReact
      style={{ height: "100vh", width: "100%" }}
      defaultZoom={zoom}
      defaultCenter={center}
    >
      {data.map((item, idx) => {
        return <CustomMarker  onMarkerClick={handleMarkerClick} key={idx} lat={item.lat} lng={item.lng} />
      })}
    </GoogleMapReact>
  );
}

Solution 2:

Try this code :

import { Map, GoogleApiWrapper, Marker } from "google-maps-react";

handleMarkerClick = (props, marker, e) => {
    // do whatever you want
};

<Marker
    onClick={this.handleMarkerClick}
></Marker>

With rest of your configuration as you require.


Post a Comment for "Google-Map-React - Javascript: How To Click On A Customized Marker"