2

I'm working on a project which uses react-google-maps (https://github.com/tomchentw/react-google-maps) library.

It works well, but we stumbled upon a problem with overlapping markers. Ideal solution to our case would be to use this plugin: https://github.com/jawj/OverlappingMarkerSpiderfier.

Is there any way to use it with react-google-maps?

Piotr Szlagura
  • 650
  • 5
  • 15

1 Answers1

6

How to OverlappingMarkerSpiderfier plugin integrate into react-google-maps

1)install npm-overlapping-marker-spiderfier package: npm i npm-overlapping-marker-spiderfier

2) once installed the following component demonstrates how to create the instance of OverlappingMarkerSpiderfier class and pass markers:

import React from "react";
import PropTypes from "prop-types";
import { MAP, MARKER } from "react-google-maps/lib/constants";


class Spiderfy extends React.Component {
  static contextTypes = {
    [MAP]: PropTypes.object
  };

  constructor(props, context) {
    super(props, context);
    const oms = require(`npm-overlapping-marker-spiderfier/lib/oms.min`)
    this.oms = new oms.OverlappingMarkerSpiderfier(this.context[MAP], {});
    this.markerNodeMounted = this.markerNodeMounted.bind(this);
  }

  markerNodeMounted(ref) {
    const marker = ref.state[MARKER];
    this.oms.addMarker(marker); 
    window.google.maps.event.addListener(marker, "spider_click", (e) => {
      if (this.props.onSpiderClick) this.props.onSpiderClick(e);
    });
  }

  render() {
    return React.Children.map(this.props.children, child =>
      React.cloneElement(child, { ref: this.markerNodeMounted })
    );
  }
}

Usage

<GoogleMap
  defaultZoom={zoom}
  defaultCenter={{
    lat: center.lat,
    lng: center.lng
  }}
>
  <Spiderfy>
    <Marker
      position={{
        lat: center.lat,
        lng: center.lng
      }}
    />
    <Marker
      position={{ lat: -37.9716929, lng: 144.772958 }}
      title="Melbourne"
    />
    <Marker
      position={{ lat: -38.132245, lng: 144.2994245 }}
      title="Geelong"
    />
    <Marker
      position={{ lat: -38.2277575, lng: 145.0447435 }}
      title="Mornington"
    />
  </Spiderfy>
</GoogleMap>

Here is a demo for your reference

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • 1
    Thank you very much for your answer! I'll check it out tomorow :) – Piotr Szlagura Apr 10 '19 at 19:38
  • Thanks for this. Will this work with custom react components instead of default google map markers? – ArcadeRenegade Jun 07 '19 at 00:17
  • Some adjustment might be needed, in the provided implementation there's a dependency to marker native object which is passed via context – Vadim Gremyachev Jun 07 '19 at 05:48
  • The demo appears to be broken (not just the expired key) - markers do not have spiderfy icon and app crashes when icon clicked. Anyone have a working react-google-maps / react code example they can share? – Becks104 Oct 05 '20 at 17:26