Emanuele
Emanuele

Reputation: 2384

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 inject these vessels inside a table. Those vessels have latitude and longitude and thanks to that I can locate them on the google-map as customized markers.

the problem I have is that I have been trying to click on these markers (or logos) but with no luck so far.

Below the code I have so far:

GoogleMap.js

import GoogleMapReact from 'google-map-react';
import { Marker } from "google-maps-react";
import InfoWindow from '../components/InfoWindowBox';

import ShipTracker from '../components/ShipTracker';
import SideBar from '../components/SideBar';
import { Ship } from '../components/ShipTracker';
import { MarkerClickHandle } from '../components/ShipTracker';

onMarkerClick = (props, marker, e) => {
    this.setState({
      selectedPlace: props.place_,
      activeMarker: marker,
      showingInfoWindow: true
    });
  };

  showDetails = place => {
    console.log(place);
  };

    render() {
        return (
            <div className="google-map">
                <GoogleMapReact
                    bootstrapURLKeys={{ key: 'My_KEY' }}
                    center={{
                        lat: 42.4,
                        lng: -71.1
                    }}
                    zoom={8}
                >
// Rendering all the logos 
                    {this.state.ships.map((ship) => {
                        return (
                            <Ship 
                                ship={ship} 
                                key={ship.CALLSIGN} 
                                lat={ship.LATITUDE} 
                                lng={ship.LONGITUDE} 
                            />
                        )
                    }
// technically this should return the clicked ship (not working)
                    {this.state.markers.map((marker, index) => {
                        return (
                        <MarkerClickHandle
                        ship={ship}
                        key={ship.CALLSIGN} 
                        lat={ship.LATITUDE} 
                        lng={ship.LONGITUDE}
                        zoom = {14}
                        key={index}
                        title={marker.title}
                        name={marker.name}
                        position={marker.position}
                        InfoWindow
                        />
                    })}
                    );
// technically this should return the info window with the clicked info about the vessel (not working)
                    <InfoWindow
                        marker={this.state.activeMarker}
                        visible={this.state.showingInfoWindow}
                    >
                    <div>
                        <h3>{this.state.selectedPlace.name}</h3>
                        <button
                            type="button"
                            onClick={this.showDetails.bind(this, this.state.selectedPlace)}
                        >Show details
                        </button>
                    </div>
                    </InfoWindow>

ShipTracker.js

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

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


const MarkerClickHandle  = ({ marker }) => {
      this.state = {
        markers: [
          {
            title: "Vessel name is: ",
            name: "",
            position: { lat, lng }
          }
        ]
      };
      this.onClick = this.onClick.bind(this);

    onClick(t, map, coord) {
      const { latLng } = coord;
      const lat = latLng.lat();
      const lng = latLng.lng();

      this.setState(previousState => {
        return {
          markers: [
            ...previousState.markers,
            {
              title: "",
              name: "",
              position: { lat, lng }
            }
          ]
        };
      });
    }
}

export { MarkerClickHandle };


const ShipTracker = ({ ships }) => {
    const handleRowClick = (rowValue) => {
        console.log(rowValue);
    };
    return (
        <div className="ship-tracker">
            <Table className="flags-table" responsive hover>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Name</th>
                        <th>Callsign</th>
                        <th>Heading</th>
                        <th>SOG</th>
                        <th>IMO</th>
                        <th>MMSI</th>
                        <th>Longitude</th>
                        <th>Latitudee</th>
                    </tr>
                </thead>
                <tbody>
                    {ships.map((ship, index) => {
                        const { IMO, NAME, CALLSIGN, HEADING, SOG, MMSI, LONGITUDE, LATITUDE } = ship;
                        const cells = [ NAME, CALLSIGN, HEADING, SOG, IMO, MMSI, LONGITUDE, LATITUDE ];
                        return (
                            <tr onClick={() => handleRowClick(ship)} key={index}>
                                <th scope="row">{index}</th>
                                {cells.map((cell) => <td>{cell}</td>)}
                            </tr>
                        );
                    })}
                </tbody>
            </Table>
        </div>
    );
};

what I tried so far:

1) I came across this source and that was useful to understand how to create a marker but unfortunately I was not able to solve the problem.

2) Another thing I tried was applying the procedure I found on this post. Despite the procedure is clear, in my case I use google-map-react instead of google-map. I know that the procedure is similar, but for some reasons I might be missing something.

3) After digging more into the problem I came across this source and it was very useful as I set the <Map> in the same way but but when it was time to set the marker I could not fix the problem and click on it.

Despite I found some useful posts I was not able to fix this issue. If anyone already used google-map-react for solving this issue, point in the right direction.

Upvotes: 3

Views: 7376

Answers (2)

Abdul Rahim Nagori
Abdul Rahim Nagori

Reputation: 3

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.

Upvotes: 0

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59318

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>
  );
}

Upvotes: 2

Related Questions