I am a beginner in programming.
I tried to create a website using the Maps JavaScript API that when you press a button with the name of a city, it takes you to that location in the map, and a marker is placed there. I have been able to run the site, but I get the following three errors in the console. If anyone knows the cause, I would like to know how to avoid the errors.
3 Errors
・you have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors
・Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘xn’)
・Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘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>
);
}
Using github copilot etc. does not solve the problem.The languages used are typescript and next.js
user49026 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.