google-maps-react - 特定 Pin 图直到点击才显示

时间:2021-04-24 22:06:06

标签: javascript reactjs google-maps

SparkNotes:

我正在使用犯罪 API 来查看热点。某些犯罪不会以经纬度记录,因此不会显示在标准(免费)犯罪应用中。

  • 我覆盖到新的纬度/经度的经纬度引脚不显示 第一次加载/或完全加载。 (google-maps-react)(经确认的纬度/经度对附近区域的每个犯罪都是有效的。)
  • 具有现有纬度/经度显示的普通别针 很好/一加载就显示出来。 (即使它们都是相同的数据数组。)
  • 我遍历空白的纬度/经度并将纬度/经度替换为该区域的粗略纬度/经度,以便它显示出来。在我的控制台日志中,我可以确认我已经覆盖了空白的纬度/经度。
  • 我希望这些记录能够了解社区/可能避免进入特定犯罪热点。

API 正常:
https://data.seattle.gov/resource/tazs-3rd5.json?$limit=20000&$offset=20000&$order=offense_id

具体项目: https://data.seattle.gov/resource/tazs-3rd5.json?$where=report_number%20in(%272020-022388%27,%272020-044620%27,%272020-043813%27,%272020-029645%27,%272020-901621%27)

完整用例(不适用于所有引脚): https://data.seattle.gov/resource/tazs-3rd5.json?crime_against_category=PERSON&mcpp=MAGNOLIA&offense_parent_group=SEX%20OFFENSES

请求帮助: 有人可以帮助如何让这些被覆盖的图钉始终显示吗?

我尝试过的事情: 强制更新/多次刷新等/减少异步时间。当我输入特定的犯罪报告编号时,那些工作,但如果我搜索绑架/偷窥,他们不会与其他人一起犯罪。

我可以确认,如果我只是在该 API 中加载所有犯罪,地图会记录所有犯罪(除了我需要的那些),就像每英尺街道上的大头针一样,但我需要的类别中的大头针不会' t 出现。 (所以我不认为这是音量问题。)

API 数据代码:

const endpoint = 'https://data.seattle.gov/resource/tazs-3rd5.json?$where=report_number%20in(%272020-022388%27,%272020-044620%27)'
const originalplaces = [];
const places = []
fetch(endpoint)
.then(blob => blob.json())
.then(data => originalplaces.push(...data));



async function returnTrue() {


  // create a new promise inside of the async function
  let promise = new Promise((resolve, reject) => {

    setTimeout(() => resolve(true), 1000) // resolve
  });


  // wait for the promise to resolve
  let result = await promise;
  // originalplaces.mcpp === 'MAGNOLIA' && originalplaces.longitude == '0E-9'   && originalplaces.longitude.replace("0E-9", "-122.385973723")
  // originalplaces.forEach(function(mcpp, i) { if (mcpp == 'MAGNOLIA') originalplaces[i] = '47.649387230'; });
  originalplaces.map(object => {

    if (object.mcpp === 'MAGNOLIA' && object.longitude === '0E-9' && object.latitude === '0E-9')

     {  object.longitude = "-122.391970804"
     object.latitude = "47.63103937"
    }


  })
  places.push(...originalplaces)


  console.log(places)


  // console log the result (true)
  console.log(result);
}

// call the function
returnTrue();

export default originalplaces;

地图代码

import React, { Component } from "react";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from "google-maps-react";

import places from './crimedata.js'

class MapView extends Component {
  constructor(props) {
    super(props)
    this.state = {
      showingInfoWindow: false,
      activeMarker: {},
      selectedPlace: {},

    };
    this.handleMarkerClick = this.handleMarkerClick.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }



  handleMarkerClick = (props, marker, e) => {
    this.setState({
      selectedPlace: places[props.placeIndex],
      activeMarker: marker,
      showingInfoWindow: true,

    });
  };

  handleClose = () => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null
      });
    }
  };

  render() {

    return (
      <Map
        google={this.props.google}
        className={"map"}
        initialCenter={{ lat: 47.6205, lng: -122.3493}}
        style={{ height: '100vh', width: '100%' }}
      >

        {places.map((place, i) => {
          return (



            <Marker
              key={i}
              onClick={this.handleMarkerClick}
              position={{
                lat: parseFloat(place.latitude),
                lng: parseFloat(place.longitude)

              }}

              icon={{

                url: place.offense_parent_group === "ASSAULT OFFENSES" ? "/googlemarkersyellow.svg"
                : place.offense_parent_group === "BURGLARY/BREAKING&ENTERING" ?"/googlemarkersdarkorange.svg"
                : place.offense_parent_group === "TRESPASS OF REAL PROPERTY" ?"/googlemarkersorange.svg"
                : place.offense_parent_group === "STOLEN PROPERTY OFFENSES" ?"/googlemarkersgreen.svg"
                : place.offense_parent_group === "SEX OFFENSES" ?"/googlemarkersblack.svg"
                : place.offense_parent_group === "DESTRUCTION/DAMAGE/VANDALISM OF PROPERTY" ?"/googlemarkersdarkgreen.svg"
                : place.offense_parent_group === "DRUG/NARCOTIC OFFENSES" ?"/googlemarkersdarkgray.svg"
                : place.offense_parent_group === "ROBBERY" ?"/googlemarkersdarkpurple.svg"
                : place.offense_parent_group === "MOTOR VEHICLE THEFT " ?"/googlemarkerspink.svg"
                : place.offense_parent_group === "HOMICIDE OFFENSES" ?"/googlemarkersteal.svg"
                : place.offense_parent_group === "ARSON" ?"/googlemarkerslightblue.svg"
                : place.offense_parent_group === "HUMAN TRAFFICKING" ?"/googlemarkersteal.svg"
                : place.offense_parent_group === "PROSTITUTION OFFENSES" ?"/googlemarkerstan.svg"

                : `/googlemarkerdefault.svg`,
                scaledSize: new window.google.maps.Size(50, 50)
              }}
              placeIndex={i}
              name={place.offense}
            />

          );
        })}

        <InfoWindow
          marker={this.state.activeMarker}
          visible={this.state.showingInfoWindow}
          onClose={this.handleClose}

        >
          <div> <h6>{this.state.selectedPlace.offense}</h6>
         <p> {'Crime: ' + this.state.selectedPlace.offense_parent_group}</p>
         <p> {'City: ' + this.state.selectedPlace.mcpp}</p>
         <p> {'Report Date: ' +this.state.selectedPlace.report_datetime}</p>
         <p> {'Report Number: ' + this.state.selectedPlace.report_number}</p>



          </div>
        </InfoWindow>
      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: process.env.REACT_APP_GOOGLEMAPS
})(MapView);


屏幕截图:

Prior to Clicking

AfterClicking

最后注意事项: 我有所有城市的覆盖,这就是为什么你在我的屏幕截图中看到 4 个引脚,但代码只有一个城市的覆盖,如果我包括所有,它真的很长。

1 个答案:

答案 0 :(得分:0)

在第一次加载代码时从 places 导入 crimedata.js 数据时,似乎存在时间问题。我可以看到 places 值在初始运行时为空 [] 然后您的位置在 crimedata.js 中的加载将在一段时间后进行。您可以在我的 working code 的控制台日志中看到这一点。

为了处理这个问题,我使用状态变量来保存 updatedPlaces 数据的值,然后在 componentDidMount 函数中,我使用了 setTimeOut 并设置了来自导入位置的 updatedPlaces 状态变量的值现在可用的数据。

然后我使用这个状态变量作为标记加载的条件。

这是代码片段:

import React, { Component } from "react";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from "google-maps-react";

import places from "./crimedata.js";
console.log("upon importing crimedata.js");
console.log(places);
class MapView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      updatedPlaces: null,
      showingInfoWindow: false,
      activeMarker: {},
      selectedPlace: {}
    };
    this.handleMarkerClick = this.handleMarkerClick.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }

  componentDidMount() {
    //console.log(places);

    setTimeout(() => {
      this.setState({
        updatedPlaces: places
      });
      console.log("timeOut in componentDidMount");
      console.log(this.state.updatedPlaces);
    }, 1000);
  }

  handleMarkerClick = (props, marker, e) => {
    this.setState({
      selectedPlace: places[props.placeIndex],
      activeMarker: marker,
      showingInfoWindow: true
    });
  };

  handleClose = () => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null
      });
    }
  };

  render() {
    return (
      <Map
        google={this.props.google}
        className={"map"}
        initialCenter={{ lat: 47.6205, lng: -122.3493 }}
        style={{ height: "100vh", width: "100%" }}
      >
        {this.state.updatedPlaces != null &&
          this.state.updatedPlaces.map((place, i) => (
            <Marker
              key={i}
              onClick={this.handleMarkerClick}
              position={{
                lat: parseFloat(place.latitude),
                lng: parseFloat(place.longitude)
              }}
              icon={{
                url:
                  place.offense_parent_group === "ASSAULT OFFENSES"
                    ? "http://maps.google.com/mapfiles/kml/paddle/ylw-blank.png"
                    : place.offense_parent_group ===
                      "BURGLARY/BREAKING&ENTERING"
                    ? "http://maps.google.com/mapfiles/kml/paddle/orange-blank.png"
                    : place.offense_parent_group === "TRESPASS OF REAL PROPERTY"
                    ? "http://maps.google.com/mapfiles/kml/paddle/orange-circle.png"
                    : place.offense_parent_group === "STOLEN PROPERTY OFFENSES"
                    ? "http://maps.google.com/mapfiles/kml/paddle/grn-blank.png"
                    : place.offense_parent_group === "SEX OFFENSES"
                    ? "http://maps.google.com/mapfiles/kml/paddle/wht-circle.png"
                    : place.offense_parent_group ===
                      "DESTRUCTION/DAMAGE/VANDALISM OF PROPERTY"
                    ? "http://maps.google.com/mapfiles/kml/paddle/grn-circle.png"
                    : place.offense_parent_group === "DRUG/NARCOTIC OFFENSES"
                    ? "http://maps.google.com/mapfiles/kml/paddle/wht-stars.png"
                    : place.offense_parent_group === "ROBBERY"
                    ? "http://maps.google.com/mapfiles/kml/paddle/purple-blank.png"
                    : place.offense_parent_group === "MOTOR VEHICLE THEFT "
                    ? "http://maps.google.com/mapfiles/kml/paddle/pink-blank.png"
                    : place.offense_parent_group === "HOMICIDE OFFENSES"
                    ? "http://maps.google.com/mapfiles/kml/paddle/ltblu-blank.png"
                    : place.offense_parent_group === "ARSON"
                    ? "http://maps.google.com/mapfiles/kml/paddle/blu-blank.png"
                    : place.offense_parent_group === "HUMAN TRAFFICKING"
                    ? "http://maps.google.com/mapfiles/kml/paddle/ltblu-circle.png"
                    : place.offense_parent_group === "PROSTITUTION OFFENSES"
                    ? "http://maps.google.com/mapfiles/kml/paddle/T.png"
                    : `http://maps.google.com/mapfiles/kml/pushpin/red-pushpin.png`,
                scaledSize: new window.google.maps.Size(50, 50)
              }}
              placeIndex={i}
              name={place.offense}
            />
          ))}

        <InfoWindow
          marker={this.state.activeMarker}
          visible={this.state.showingInfoWindow}
          onClose={this.handleClose}
        >
          <div>
            {" "}
            <h6>{this.state.selectedPlace.offense}</h6>
            <p> {"Crime: " + this.state.selectedPlace.offense_parent_group}</p>
            <p> {"City: " + this.state.selectedPlace.mcpp}</p>
            <p> {"Report Date: " + this.state.selectedPlace.report_datetime}</p>
            <p> {"Report Number: " + this.state.selectedPlace.report_number}</p>
          </div>
        </InfoWindow>
      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: "YOUR_API_KEY"
})(MapView);
相关问题