【问题标题】:Add polyline to react-hook-google-maps将折线添加到 react-hook-google-maps
【发布时间】:2021-05-26 12:15:00
【问题描述】:

我有一个简单的代码,用于渲染谷歌地图。我在向其添加折线时遇到问题。

import React from "react";
import { useGoogleMaps } from "react-hook-google-maps";

export const Map = React.memo(function Map() {  
  const pointA = {  lat: 0, lng: -180 };
  var polyline = require( 'google-polyline' );
  const { ref, map, google } = useGoogleMaps(
    "AIzaSyC4Z5Qz97EWcoCczNn2IcYvaYG0L9pe6Rk",
    {
      zoom: 4,
      center: pointA,
    },
  );
 if (map) {
   var poly = polyline.decode('_jpeFn||hVf}qcBvnixEfwtoF_fic_Afh|w@~u`zC');
  console.log(JSON.stringify(poly));
  var polyline = new google.maps.Polyline({
    path: poly,
    geodesic: true,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2,
  }); 
  polyline.setMap(map);
  }

return (
    <div>
      <div ref={ref} style={{ width: 600, height: 400 }} />
    </div>
  );
});

如何在地图上添加给定的折线?如果您想要多段线的解码版本。

const poly = [
    { lat: 37.772, lng: -122.214 },
    { lat: 21.291, lng: -157.821 },
    { lat: -18.142, lng: 178.431 },
    { lat: -27.467, lng: 153.027 },
  ];

我正在使用打字稿。任何帮助将不胜感激。

【问题讨论】:

    标签: typescript google-maps react-hooks


    【解决方案1】:

    好的,我的代码是正确的。显然,我的

    var poly = polyline.decode('_jpeFn||hVf}qcBvnixEfwtoF_fic_Afh|w@~u`zC');
    

    给出一个数组数组而不是对象数组。所以必须添加下面的代码来将数组数组转换为对象数组。

    var poly1 = poly.map(function(x: any) { 
        return { 
          lat: x[0], 
          lng: x[1] 
        };
      });
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 2021-12-31
      • 2019-04-09
      • 2013-06-29
      • 2021-10-20
      • 2018-07-20
      • 1970-01-01
      • 2023-02-12
      • 2016-03-26
      相关资源
      最近更新 更多