简体   繁体   中英

Adding Marker to Google Maps in google-map-react with functional components

I am using the google-map-react NPM package to create a Google Map and several markers. The information for the coordinates, infowindow, icon, etc. will come from a JSON file. I have added onGoogleApiLoaded and yesIWantToUseGoogleMapApiInternals.

This is what my code currently looks like, with the markers being inside this file for the time being

import React, { useEffect } from 'react'
import GoogleMapReact from 'google-map-react'

let mapOptions = {
    center: { lat: 39.56939, lng: -40.0000 },
    zoom: 3.5,
    disableDefaultUI: true,
    gestureHandling: 'none',
    zoomControl: false,
    scaleControl: false,
    zoomControlOptions: false,
    scrollwheel: false,
    panControl: false,
  };
function ModelsMap({ data, state }) {

    console.log(data.models)

    function initMap() {

        let markers = [
         /.../
        ];

        function Marker(props) {

            let marker = new google.maps.marker({
                position: props.coords,
                content: props.content,
                icon: props.icon,
                map: map
            });

            let infoWindow = new google.maps.InfoWindow({
                content: props.content
            });

            Marker.addListener('click', function () {
                infoWindow.open(map, marker);
            })
        }
    }
     // useEffect(initMap, []); it will only render once 
    return (
        <div style={{height: '100vh', width: '100%' }}>
            <GoogleMapReact
                bootstrapURLKeys={{ key: "YOUR_API_KEY" }}
                defaultCenter={{lat: 39.56939, lng: -40.0000 }}
                defaultZoom={3.5}
                options={mapOptions}
                yesIWantToUseGoogleMapApiInternals
                onGoogleApiLoaded={({ map, maps }) => ModelsMap(map, maps)}
                >
                
            </GoogleMapReact>
        </div>
    );
}
export default ModelsMap;

I have followed the solution listed on This other stack overflow post , but that didn't work either.

Base on the answers on the StackOverflow you provided they uses new maps.Marker() to create a new Google Maps marker. If you want to get the value of your coordinates,icons and different properties of marker from a json data, you need to put this new maps.Marker() to loop through each json data. Below should be the value of your ModelsMap . Don't for get to import your json file.

const ModelsMap = (map, maps) => {
    //instantiate array that will hold your Json Data
    let dataArray = [];
    //push your Json Data in the array
    {
      data.map((markerJson) => dataArray.push(markerJson));
    }

    //Loop through the dataArray to create a marker per data using the coordinates in the json
    for (let i = 0; i < dataArray.length; i++) {
      let marker = new maps.Marker({
        position: { lat: dataArray[i].lat, lng: dataArray[i].lng },
        map,
        label: dataArray[i].id,
      });
    }
  };

Here is a sample code that shows this . Please use your own API key for this to work.

Side Note: I removed the API Key in your question. Please don't share your API keys in public sites in the future.

enable javascript map api from your google cloud console

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM