GoogleMapが動かない・・?

らら
らら

はじめに

過去のソースをひっぱってきて・・ごにょごにょしてたら・・

う。動かない・・・・?

調べてみた・・

原因は、単にmapのstyleに幅、高さの指定をしていなかっただけ・・・

ただ、調査中にブラウザーに警告が出ていて・・

2024年2月21日に・・・ってある・・

現在では、過去の同様のコードを利用しているサイトはまだ、動いているけど・・


As of February 21st, 2024, google.maps.Marker is deprecated. Please use google.maps.marker.AdvancedMarkerElement instead. At this time, google.maps.Marker is not scheduled to be discontinued, but google.maps.marker.AdvancedMarkerElement is recommended over google.maps.Marker. While google.maps.Marker will continue to receive bug fixes for any major regressions, existing bugs in google.maps.Marker will not be addressed. At least 12 months notice will be given before support is discontinued. Please see https://developers.google.com/maps/deprecations for additional details and https://developers.google.com/maps/documentation/javascript/advanced-markers/migration for the migration guide.

google.maps.Marker(v3.56)は、2024 年 2 月 21 日にサポートが終了します。
つきましては、新しい google.maps.marker.AdvancedMarkerElement クラスに移行することをおすすめします。
高度なマーカーでは、従来の google.maps.Marker クラスと比べて、大幅な改善が加えられています。

上記でみると、サポートしないよってこと?AdvancedMarkerElementにしろと?。。。。

AdvancedMarkerElementだとGoogle Maps Platformで取得したAPI KEYとは別にmapidもいるみたい。。

まぁ、新しいAdvancedMarkerElementをためしてみることにした。

古い呼び出しは・・下記


<script src ="https://maps.google.com/maps/api/js?key=APIKEY&language=ja"></script>

新しい呼び出し

今回は、古いソースをなんなく動かしたので。。

こちらは、ES6とPromiseに対応した記述ではありません。w

マーカデータも古い形式で動くように・

・・

開発中のみは・・v=beta


<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap&libraries=marker&v=beta" defer></script>

書き換えたソース

GoogleMapで複数のマーカーを表示するやつ

mapId: 'DEMO_MAP_ID' は検証用、実際にGoogle Maps Platformで取得したmapidを使う・・


<script>
var markers  = [
['<p>店舗A</p>','35.12998537','136.9797625'],
['<p>店舗B</p>','35.16958088','136.8816366'],
['<p>店舗C</p>','35.14625778','137.0210802'],
];
function initMap() {
	var myOptions = {
		zoom: 12,
		center: new google.maps.LatLng(35.16991042521872,136.90756276140058),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		streetViewControl:false,
		mapId: 'DEMO_MAP_ID',
	};
	var map = new google.maps.Map(document.getElementById("map"), myOptions);
	var infoWindow = new google.maps.InfoWindow();
	markers.forEach( function(value, i) {
		var gtitle	= markers[i][0];
		var glat	= parseFloat(markers[i][1]);
		var glng	= parseFloat(markers[i][2]);
		var Img = document.createElement("img");
		Img.src = "マーカーのURL/marker1.png";
		Img.width	= 40;	// 横サイズ(px)
		Img.height	= 40;	// 縦サイズ(px)
		var marker = new google.maps.marker.AdvancedMarkerView({
			position : {
				'lat': glat,
				'lng': glng
			},
			map,
			title: gtitle,
			content: Img
		});
		marker.addListener("click", ({ domEvent, latLng }) => {
			const { target } = domEvent;
			infoWindow.close();
			infoWindow.setContent(marker.title);
			infoWindow.open(marker.map, marker);
		});
	});
}
window.initMap = initMap;
</script>

<style>
#map {
	height: 600px;
}
</style>
</head>
<body>
	<div id="map"></div>
</body>
</html>

google.maps.MarkerImage はAdvancedMarkerViewではiconがつかえなくなったのでhtmlタグでimgタグを入れるように変更・・・

google.maps.event.addListener → marker.addListener

'DEMO_MAP_ID'とv=betaでは動作した・・・本番はまだ・・・試してない・・weeklyとか?

新しい記述は・・・

ESでgoogleサンプルコードを変更しています。

こちらもAPIキーとMAPIDがあります。APIキー、MAPIDが正しくないと地図が表示されません

サンプルのようにマーカーアニメーションなど表現方法が増えています。。


<html lang='ja'>
<head>
<meta charset='utf-8'>
	<title>Advanced Markers with HTML</title>
	<script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js"></script>
	<script src="https://use.fontawesome.com/releases/v6.2.0/js/all.js"></script>
<style>
:root {
	--building-color: #FF9800;
	--house-color: #0288D1;
	--shop-color: #7B1FA2;
	--warehouse-color: #558B2F;
}
/*
 * Optional: Makes the sample page fill the window.
 */
html,
body {
	height: 100%;
	margin: 0;
	padding: 0;
}
/*
 * Always set the map height explicitly to define the size of the div element
 * that contains the map.
 */
#map {
	height: 100%;
	width: 100%;
}
/*
 * Property styles in unhighlighted state.
 */
.property {
	align-items: center;
	background-color: #FFFFFF;
	border-radius: 50%;
	color: #263238;
	display: flex;
	font-size: 14px;
	gap: 15px;
	height: 30px;
	justify-content: center;
	padding: 4px;
	position: relative;
	position: relative;
	transition: all 0.3s ease-out;
	width: 30px;
}
.property::after {
	border-left: 9px solid transparent;
	border-right: 9px solid transparent;
	border-top: 9px solid #FFFFFF;
	content: "";
	height: 0;
	left: 50%;
	position: absolute;
	top: 95%;
	transform: translate(-50%, 0);
	transition: all 0.3s ease-out;
	width: 0;
	z-index: 1;
}
.property .icon {
	align-items: center;
	display: flex;
	justify-content: center;
	color: #FFFFFF;
}
.property .icon svg {
	height: 20px;
	width: auto;
}
.property .details {
	display: none;
	flex-direction: column;
	flex: 1;
}
.property .address {
	color: #9E9E9E;
	font-size: 10px;
	margin-bottom: 10px;
	margin-top: 5px;
}
.property .features {
	align-items: flex-end;
	display: flex;
	flex-direction: row;
	gap: 10px;
}
.property .features > div {
	align-items: center;
	background: #F5F5F5;
	border-radius: 5px;
	border: 1px solid #ccc;
	display: flex;
	font-size: 10px;
	gap: 5px;
	padding: 5px;
}
/*
 * Property styles in highlighted state.
 */
.property.highlight {
	background-color: #FFFFFF;
	border-radius: 8px;
	box-shadow: 10px 10px 5px rgba(0, 0, 0, 0.2);
	height: 80px;
	padding: 8px 15px;
	width: auto;
}
.property.highlight::after {
	border-top: 9px solid #FFFFFF;
}
.property.highlight .details {
	display: flex;
}
.property.highlight .icon svg {
	width: 50px;
	height: 50px;
}
.property .bed {
	color: #FFA000;
}
.property .bath {
	color: #03A9F4;
}
.property .size {
	color: #388E3C;
}
/*
 * House icon colors.
 */
.property.highlight:has(.fa-house) .icon {
	color: var(--house-color);
}
.property:not(.highlight):has(.fa-house) {
	background-color: var(--house-color);
}
.property:not(.highlight):has(.fa-house)::after {
	border-top: 9px solid var(--house-color);
}
/*
 * Building icon colors.
 */
.property.highlight:has(.fa-building) .icon {
	color: var(--building-color);
}
.property:not(.highlight):has(.fa-building) {
	background-color: var(--building-color);
}
.property:not(.highlight):has(.fa-building)::after {
	border-top: 9px solid var(--building-color);
}
/*
 * Warehouse icon colors.
 */
.property.highlight:has(.fa-warehouse) .icon {
	color: var(--warehouse-color);
}
.property:not(.highlight):has(.fa-warehouse) {
	background-color: var(--warehouse-color);
}
.property:not(.highlight):has(.fa-warehouse)::after {
	border-top: 9px solid var(--warehouse-color);
}
/*
 * Shop icon colors.
 */
.property.highlight:has(.fa-shop) .icon {
	color: var(--shop-color);
}
.property:not(.highlight):has(.fa-shop) {
	background-color: var(--shop-color);
}
.property:not(.highlight):has(.fa-shop)::after {
	border-top: 9px solid var(--shop-color);
}
</style>
	<!-- prettier-ignore -->
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
				({key: "API KEY", v: "weekly"});</script>
<script>
async function initMap() {
	// Request needed libraries.
	const { Map } = await google.maps.importLibrary("maps");
	const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
	const center = { lat: 35.16940018488393, lng: 136.89848329017295 };
	const map = new Map(document.getElementById("map"), {
		zoom: 14,
		center,
		mapId: 'DEMO_MAP_ID',
	});
	for (const property of properties) {
		const AdvancedMarkerElement = new google.maps.marker.AdvancedMarkerElement({
			map,
			content: buildContent(property),
			position: property.position,
			title: property.description,
		});
		AdvancedMarkerElement.addListener("click", () => {
			toggleHighlight(AdvancedMarkerElement, property);
		});
	}
}
function toggleHighlight(markerView, property) {
	if (markerView.content.classList.contains("highlight")) {
		markerView.content.classList.remove("highlight");
		markerView.zIndex = null;
	} else {
		markerView.content.classList.add("highlight");
		markerView.zIndex = 1;
	}
}
function buildContent(property) {
	const content = document.createElement("div");
	content.classList.add("property");
	content.innerHTML = `
		<div class="icon">
			<i aria-hidden="true" class="fa fa-icon fa-${property.type}" title="${property.type}"></i>
			<span class="fa-sr-only">${property.type}</span>
		</div>
		<div class="details">
			<div class="address">${property.address}</div>
			<div class="features">
				<div>
					<i aria-hidden="true" class="fa fa-bed fa-lg bed" title="bedroom"></i>
					<span class="fa-sr-only">bedroom</span>
					<span>${property.bed}</span>
				</div>
				<div>
					<i aria-hidden="true" class="fa fa-bath fa-lg bath" title="bathroom"></i>
					<span class="fa-sr-only">bathroom</span>
					<span>${property.bath}</span>
				</div>
				<div>
					<i aria-hidden="true" class="fa fa-ruler fa-lg size" title="size"></i>
					<span class="fa-sr-only">size</span>
					<span>${property.size} ft<sup>2</sup></span>
				</div>
			</div>
		</div>
		`;
	return content;
}
const properties = [
	{
		address: "名古屋市中区丸の内2-17-30 ie桜通伏見ビルディング8F",
		description: "会社",
		type: "home",
		bed: 5,
		bath: 4.5,
		size: 300,
		position: {
			lat: 35.16985504172418,
			lng: 136.89766783941056,
		},
	},
	{
		address: "愛知県名古屋市中村区名駅4丁目7",
		description: "ミッドランド",
		type: "building",
		bed: 4,
		bath: 3,
		size: 200,
		position: {
			lat: 35.17017712031541,
			lng: 136.8852071342918,
		},
	},
	{
		address: " 愛知県名古屋市中区錦2丁目9−6",
		description: "スペースプラス中区丸の内2丁目",
		type: "warehouse",
		bed: 4,
		bath: 4,
		size: 800,
		position: {
			lat: 35.17108742966187,
			lng: 136.8984004855156,
		},
	},
	{
		address: "愛知県名古屋市中区丸の内2丁目19−3",
		description: "セブン-イレブン",
		type: "store-alt",
		bed: 2,
		bath: 1,
		size: 210,
		position: {
			lat: 35.174413434696476,
			lng: 136.89874649047852,
		},
	},
];
initMap();
</script>
</head>
<body>
	<div id="map"></div>
</body>
</html>

表示

GoogleMAP座標

さいごに

V2,V3と・・・今回と、何回書き換えするのよぉ・・・

関連記事