尝试 Maps JavaScript API 并收到错误

问题描述 投票:0回答:1

我是编程初学者。 我尝试使用 Maps JavaScript API 创建一个网站,当您按下带有城市名称的按钮时,它会将您带到地图中的该位置,并在那里放置一个标记。我已经能够运行该网站,但在控制台中出现以下三个错误。如果有人知道原因,我想知道如何避免这些错误。

3 个错误

・您已在此页面上多次包含 Google Maps JavaScript API。这可能会导致意外错误

・未捕获(承诺中)类型错误:无法读取未定义的属性(读取“xn”)

・未捕获(承诺中)类型错误:无法读取未定义的属性(读取“Fg”)

index.tsx

import { useEffect, useState } from 'react';

declare global {
  interface Window {
    initMap: () => void;
  }
}

type MapLocation = {
  name: string;
  lat: number;
  lng: number;
};
const locations:MapLocation[] = [
  { name: '東京', lat: 35.6811673, lng: 139.7670516 },
  { name: '大阪', lat: 34.6937378, lng: 135.5021651 },
  { name: '名古屋', lat: 35.1814511, lng: 136.9065574 },
  { name: '福岡', lat: 33.5903548, lng: 130.4017151 },
  { name: '札幌', lat: 43.061771, lng: 141.354451 },
];

export default function Home() {
  const [map, setMap] = useState<google.maps.Map | null>(null);
  useEffect(() => {
    if (!window.google) {
        window.initMap = function() {
          const mapElement = document.getElementById('map');
          if (mapElement) {
            const initialMap = new google.maps.Map(mapElement, {
                center: { lat: locations[0].lat, lng: locations[0].lng },
                zoom: 15,
              });
              setMap(initialMap);
          }
    };
    const script = document.createElement('script');
    script.src = `https://maps.googleapis.com/maps/api/js?key=map_api&callback=initMap`;
    script.defer = true;
    script.async = true;
    document.head.appendChild(script);
    }
  }, []);

  const handleClick = (location: MapLocation) => {
    if(map) {
      map.setCenter(new google.maps.LatLng(location.lat, location.lng));
      new google.maps.Marker({
        position: new google.maps.LatLng(location.lat, location.lng),
        map: map,
        title: location.name,
      });
    }
  };

  return (
    <div>
      <div id="map" style={{ width: '100vw', height: '70vh' }}></div>
      {locations.map((location, index) => (
        <button key={index} onClick={() => handleClick(location)}>
          {location.name}
        </button>
      ))}
    </div>
  );
}

使用github copilot等并不能解决问题。使用的语言是typescript和next.js

typescript google-maps next.js
1个回答
0
投票

我不知道为什么我无法访问帐户来获取免费的创业商业计划模板。我怎样才能访问这些信息。这是错误消息。 87f605ac4caca373 请告诉我如何访问模板 谢谢布兰登和克里斯蒂娜·甘农

© www.soinside.com 2019 - 2024. All rights reserved.