Simple Map
Sample code for Google Maps Platform JavaScript API author(s): Justin Poehnelt
by Wolf
HTML
<!DOCTYPE html>
<!--
@license
Copyright 2019 Google LLC. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
-->
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!--
The `defer` attribute causes the callback to execute after the full HTML
document has been parsed. For non-blocking uses, avoiding race conditions,
and consistent behavior across browsers, consider loading using Promises
with https://www.npmjs.com/package/@googlemaps/js-api-loader.
-->
<script
src="https://maps.googleapis.com/maps/api/js?callback=initMap&v=beta&libraries=places,marker"
defer
></script>
</body>
</html>
CSS
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/*
* Always set the map height explicitly to define the size of the div element
* that contains the map.
*/
#map {
height: 100%;
}
/*
* Optional: Makes the sample page fill the window.
*/
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
let map;
let centerCoordinates = {
lat: 47.3769,
lng: 8.5417
};
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
mapId: "7af05ad40d6f17b9",
center: centerCoordinates,
zoom: 14,
});
findPlace();
}
async function findPlace() {
const request = {
query: "Haus Hiltl, Zürich",
fields: ["displayName", "location", "iconBackgroundColor" /*,"icon"*/],
locationBias: centerCoordinates,
};
google.maps.places.Place.findPlaceFromQuery(request)
.then((response) => {
console.log("Got " + response.places.length + " places");
if (response.places.length) {
return response.places;
}
throw {
result: "No results"
};
})
.then((places) => {
const place = places[0];
const loc = place.location;
const name = place.displayName;
const bg_color = place.iconBackgroundColor;
//console.log(`${place.icon}`);
const glyph = document.createElement("img")
glyph.src = "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png";
glyph.style.width = "100%";
console.log("Got place " + name + " at " + loc);
const pinView = new google.maps.marker.PinView({
background: bg_color,
borderColor: bg_color,
glyph: glyph,
scale: 1.5,
});
const marker = new google.maps.marker.AdvancedMarkerView({
map,
position: loc,
title: name,
content: pinView.element,
});
map.setCenter(loc);
})
.catch((error) => {
console.log(error);
});
}