google maps api不为DirectionsService()

时间:2017-09-19 04:10:03

标签: javascript reactjs google-maps-api-3 create-react-app

我试图使用google maps api v3 with react,但似乎有些google地图服务在使用react时没有加载。我已尝试通过this tutorial延迟加载脚本,只是直接在我的index.html文件中加载脚本,但无济于事。我使用create-react-app和以下依赖项:

"classnames": "^2.2.5",
"invariant": "^2.2.2",
"node-sass-chokidar": "0.0.3",
"npm-run-all": "^4.1.1",
"prop-types": "^15.5.10",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-redux": "^5.0.6",
"react-scripts": "1.0.13",
"redux": "^3.7.2"

如果我从我的反应应用程序中获取DirectionsService代码的实例化并包含GMAP API,就像我使用React codepen一样,那么似乎所有Google地图依赖项都在加载。实际上,如果我从代码笔中删除对DirectionsService代码的任何引用,那么仍然会在网络选项卡中加载directions.js文件。

google map dependencies are loading in code pen

但是,通过反应,这就是我的网络选项卡的样子:

no directions service

有没有人经历过这样的事情?

1 个答案:

答案 0 :(得分:0)

事实证明,DirectionsService()需要在地图之前实例化。

  loadMap(node) {
    if (this.props && this.props.google) {
      const { google } = this.props;

      // instantiate Direction Service first
      this.directionsService = new google.maps.DirectionsService();

      this.directionsDisplay = new google.maps.DirectionsRenderer({
        suppressMarkers: true,
      });

      const zoom = 13;
      const mapTypeId = google.maps.MapTypeId.ROADMAP;
      const lat = 37.776443;
      const lng = -122.451978;
      const center = new google.maps.LatLng(lat, lng);

      const mapConfig = Object.assign({}, {
        center,
        zoom,
        mapTypeId,
      });


      this.map = new google.maps.Map(node, mapConfig);

      this.directionsDisplay.setMap(this.map);

      // make the map instance available to other components as it is just data
      this.props.dispatchGoogleMap(this.map);
    }
  }