简体   繁体   中英

Linking JSON File to google-map-react to show marker on map

I am trying to link my JSON file to google-map-react. However, my JSON coordinates do not have "lat" and "lng" format but just [ 123.231, 39.234]. I'd tried to use

const data = [{ lat: location[0], lng: location[1] }]

But, it does not work :/

This is my JSON file

{
"_id" : ObjectId("5c3a42605a498f045d2e7a81"),
"name" : "asdfsadf",
"description" : "asdfasdf",
"location" : [ 
    37.556547032646, 
    37.556547032646
],
"state" : "Seoul",
}

And, this is the JSON that was used with google-map-react

[
  {
    "id": 123,
    "title": "Think Company",
    "address": [
      {
        "id": 1236,
        "city": "Helsinki",
        "lat": "60.190711",
        "lng": "24.907195"
      }
    ]
  },
]

Here is my code for Map

import React, { Component } from "react";
import GoogleMapReact from "google-map-react";
import pin from "./g.png";

const markerStyle = {
  position: "absolute",
  width: "25px",
  height: "30px",
  top: "100%",
  left: "100%",
  transform: "translate(-50%, -100%)"
};
const data = [{ lat: location[0], lng: location[1] }];

export class Map extends Component {
  static defaultProps = {
    center: {
      lat: 37.5665,
      lng: 126.978
    },
    zoom: 10
  };

  render() {
    return (
      <div style={{ height: "100vh", width: "80%" }}>
        <GoogleMapReact
           bootstrapURLKeys={{
            key: ""
          }}
          defaultCenter={this.props.center}
          defaultZoom={this.props.zoom}
        >
          {this.props.locations.map(item => {
            if (item.address.length !== 0) {
              return item.address.map(i => {
                return (
                  <div key={i.id} lat={i.lat} lng={i.lng}>
                    <img style={markerStyle} src={pin} alt="pin" />
                  </div>
                 );
              });
            }
          })}
        </GoogleMapReact>
      </div>
    );
   }
}

export default Map;

Given the provided data format:

const data = [
  {
    _id: ObjectId("5c3a42605a498f045d2e7a81"),
    name: "asdfsadf",
    description: "asdfasdf",
    location: [37.556547032646, 37.556547032646],
    state: "Seoul"
  },
  ///...
]

markers could be rendered like this

{data.map(item => {
    return (
      <div lat={item.location[0]} lng={item.location[1]}>
        <img style={markerStyle} src={pin} alt="pin" />
      </div>
    );
})} 

Demo

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