burakkesepara
burakkesepara

Reputation: 316

Polygon not appearing in react-google-maps

I am trying to implement polygons into react-google-maps plugin but it is not working. It has no errors but also i can not see any polygons at map.

I can see the map at the page, also markers are appearing. But i can not see any polygon right now.

I am sharing my code below here, any help would be really appreciated.

const coords = [
{lat: 29.047487,lng: 41.023164},
{lat: 29.0459633,lng: 41.0212904},
{lat: 29.0449333,lng: 41.0167573},
{lat: 29.0393543,lng: 41.0106695},
{lat: 29.032917,lng: 41.0049697},
{lat: 29.0226173,lng: 41.0061356},
{lat: 29.0078545,lng: 41.0039334},
{lat: 29.0201283,lng: 40.9765933},
{lat: 29.0319729,lng: 40.9657708},
{lat: 29.0784073,lng: 40.9536501},
{lat: 29.0944576,lng: 40.9493068},
{lat: 29.0975475,lng: 40.9514461},
{lat: 29.1052294,lng: 40.9647986},
{lat: 29.097338,lng: 40.978242},
{lat: 29.0931273,lng: 40.9835914},
{lat: 29.0858746,lng: 40.987738},
{lat: 29.056509,lng: 40.998902},
{lat: 29.061456,lng: 41.008443},
{lat: 29.0617561,lng: 41.0104752},
{lat: 29.0595245,lng: 41.0126772},
{lat: 29.052014,lng: 41.018198},
{lat: 29.047487,lng: 41.023164}];

const MyMapComponent = compose(
withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=MY_API_KEY_IS_HERE&v=3.exp&libraries=geometry,drawing,places",
    loadingElement : <div style={{height: window.innerHeight - 80}}/>,
    containerElement : <div style={{height: window.innerHeight - 80, width: window.innerWidth}}/>,
    mapElement : <div style={{height: window.innerHeight - 80}}/>
}),
withScriptjs,
withGoogleMap)((props) =>
<GoogleMap
    defaultZoom={9}
    defaultCenter={{lat: 41.015137, lng: 28.979530}}
>
    {props.isMarkerShown && <Marker position={{lat: 41.015137, lng: 28.979530}}/>}
    <Polygon
        path={coords}
        key={1}
        options={{
            fillColor: "#000",
            fillOpacity: 0.4,
            strokeColor: "#000",
            strokeOpacity: 1,
            strokeWeight: 1
        }}
        onClick={() => {
            console.log("ahmet")
        }}/>
</GoogleMap>);

renderTripMap() {

    return <div className="animated fadeIn">
        {this.renderButtons()}
        <MyMapComponent isMarkerShown/>
    </div>
}

Upvotes: 2

Views: 7692

Answers (3)

dhruv10
dhruv10

Reputation: 169

Sometimes, the Polygon wouldn't appear but would appear when you change the JSX code for Polygon (wrap it in or out of a div) and it would render due to HMR.

It may seem unrelated but I was getting a performance warning with useJsApiLoader (alternate of <LoadScript />) saying this:

Performance warning! Loadscript has been reloaded unintentionally! You should not pass libraries prop as new array. Please keep an array of libraries as static class property for Components and PureComponents, or just a const variable outside of component, or somewhere in config files or ENV variables

as I was doing something like this

const { isLoaded } = useLoadScript({
    googleMapsApiKey: GOOGLE_API_KEY,
    libraries: ['places'],
  });

And, when I resolved this warning the Polygon appeared perfectly on each render. I just updated to:

const libraries = ['places'];
const { isLoaded } = useLoadScript({
    googleMapsApiKey: GOOGLE_API_KEY,
    libraries,
  });

When I found more, it seems some issue with useEffect comparison described here

Reference: https://github.com/JustFly1984/react-google-maps-api/issues/238

Upvotes: 0

Jagtar Singh
Jagtar Singh

Reputation: 211

Here is all about polygon and draging tools


 import React from "react"
 import {
withGoogleMap,
GoogleMap,
Marker,
withScriptjs,
} from "react-google-maps";
import DrawingManager from "react-google-maps/lib/components/drawing/DrawingManager";

import { MarkerWithLabel } from "react-google-maps/lib/components/addons/MarkerWithLabel";
import { Polygon } from "react-google-maps";
import { compose, withProps } from "recompose";

function GoogleMapsForDelivertCharges() {
// getModalStyle is not a pure function, we roll the style only on   the first render
const [open, setOpen] = React.useState(false);
const [cordinates, setCordinates] = React.useState([
    [
        {
            lat: 36.95017264518586,
            lng: -98.88559984996449,
        },
        {
            lat: 36.70394136086435,
            lng: -88.07505297496449,
        },
        {
            lat: 31.691080846084553,
            lng: -94.53501391246449,
        },
    ],

    [
        {
            lat: 36.879901722288025,
            lng: -124.06626391246449,
        },
        {
            lat: 37.961800398724435,
            lng: -110.61899828746449,
        },
        {
            lat: 29.53553533552923,
            lng: -107.23520922496449,
        },
        {
            lat: 28.61376794407866,
            lng: -122.30845141246449,
        },
    ],
    [
        {
            lat: 48.65307495113541,
            lng: -112.36842037145917,
        },
        {
            lat: 46.640219756834924,
            lng: -104.72193599645917,
        },
        {
            lat: 43.729651946710675,
            lng: -113.15943599645917,
        },
    ],
]);

const MyMapComponent = compose(
    withProps({
        googleMapURL:
            "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap,
)((props) => (
    <GoogleMap
        defaultZoom={3}
        defaultCenter={
            new window.google.maps.LatLng(
                36.95017264518586,
                -98.88559984996449,
            )
        }>
        {/* {props.isMarkerShown && (
            <Marker position={{ lat: 26.9124, lng: 75.7873 }} />
        )} */}
        <MarkerWithLabel
            position={{ lat: 36.95017264518586, lng: -98.88559984996449 }}
            labelAnchor={new window.google.maps.Point(0, 0)}
            labelStyle={{
                backgroundColor: "yellow",
                fontSize: "20px",
                padding: "8px",
            }}>
            <div>YOUR HERE!</div>
        </MarkerWithLabel>

        <DrawingManager
            defaultDrawingMode={
                window.google.maps.drawing.OverlayType.POLYGON
            }
            onPolygonComplete={function (polygon) {
                OpenModalBox(polygon);
                // console.log(polygon);
            }}
            defaultOptions={{
                drawingControl: true,
                drawingControlOptions: {
                    position: window.google.maps.ControlPosition.TOP_CENTER,
                    draggable: true,
                    drawingModes: [
                        window.google.maps.drawing.OverlayType.POLYGON,
                        window.google.maps.drawing.OverlayType.RECTANGLE,
                        // window.google.maps.drawing.OverlayType.CIRCLE,
                        // window.google.maps.drawing.OverlayType.POLYLINE,
                    ],
                },
                rectangleOptions: {
                    draggable: true,
                    editable: true,
                    strokeColor: "#00FF00",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#00FF00",
                    fillOpacity: 0.35,
                    onRightClick: function (event) {
                        alert("Right Clicked");
                    },
                },
                // circleOptions: {
                //  draggable: true,
                //  editable: true,
                //  strokeColor: "#FF0000",
                //  strokeOpacity: 0.8,
                //  strokeWeight: 2,
                //  fillColor: "#FF0000",
                //  fillOpacity: 0.35,
                //  zIndex: 1,
                // },
                polygonOptions: {
                    draggable: true,
                    editable: true,
                    strokeColor: "#00FF00",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#00FF00",
                    fillOpacity: 0.35,
                    onRightClick: function (event) {
                        alert("Right Clicked");
                    },
                },
            }}
        />
        <Polygon
            draggable={true}
            editable={true}
            onClick={function (event) {
                alert("clicked");
            }}
            options={{
                strokeColor: "#FF0000",
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: "#FF0000",
                fillOpacity: 0.35,
            }}
            paths={cordinates}
        />
    </GoogleMap>
));
// Google Map End  here
const OpenModalBox = (polygon) => {
    const coords = polygon
        .getPath()
        .getArray()
        .map((coord) => {
            return {
                lat: coord.lat(),
                lng: coord.lng(),
            };
        });
    console.log("OpenModal", coords);
    // setCordinates([...cordinates, coords]);
    // alert("OpenModal");
};
console.log(cordinates);
return (
    <div>
        <MyMapComponent />
    </div>
);
  }

    export default React.memo(GoogleMapsForDelivertCharges);

`

Upvotes: 0

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59388

In fact, the polygon is getting displayed, but seems not in the place where you expect it to.

Once lat and lng are interchanged

const reversedCoords = coords.map( ll => {
    return { lat: ll.lng, lng: ll.lat }
}); 

the polygon is getting visible within viewport.

Demo

Upvotes: 6

Related Questions