How to add a map on your app using the googlemap API.
Basically, it can be realized by writing [Official document] 1 ~~ along copy and paste ~~, but I am a Javascript beginner and it took a long time to decipher, so I will start the same thing I'll share it for you.
・ Map display ・ Display of search box ・ Map and search box decoration
With a little modification, It can also be decorated.
only this.
The following is a quote from [Official Document] 1. The point is to describe libraries = places in the API call script. This allows you to load the library that switches the screen to the search & search position.
sample.html
<!DOCTYPE html>
<html>
<head>
<title>Places Search Box</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
#"Key=YOUR_Describe the acquired API key in the "API" part
#Since we will add a search function this time, we will use the Places library, so "libraries"=places ”added
#"V="Weekly" indicates the update frequency of the map itself. If nothing is described, it will be updated once a quarter, and with this description, it will be updated weekly to keep it up to date, so you do not need to describe it separately.
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initAutocomplete&libraries=places&v=weekly"
defer
></script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script src="./index.js"></script>
</head>
<body>
#Display the map with javascript at the id specified here.
<input
id="pac-input"
class="controls"
type="text"
placeholder="Search Box"
/>
<div id="map"></div>
</body>
</html>
If you open the browser in this state, you will find only a search box. Let's go to the next.
The following is also a quote from [Official Document] 1, but it took time to find out where the description came from one by one. ..
For beginners, I would like to briefly explain the description of js. const ~~ defines a constant "~~" there. function ~~ is a function. google.maps is an object that specifies the map itself.
index.js
function initAutocomplete() {
//This is the default setting of the map.
const map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -33.8688, lng: 151.2195 },
zoom: 13,
mapTypeId: "roadmap",
});
const input = document.getElementById("pac-input");
const searchBox = new google.maps.places.SearchBox(input);
////"SearchBox class"Is a method of the Places library. Argument is input(There is an inputField on the document)。
////[https://developers.google.com/maps/documentation/javascript/reference/places-widget#SearchBox]
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
////"ControlPosition"The class positions the controller.
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/ControlPosition/
////https://developers.google.com/maps/documentation/javascript/examples/control-positioning
map.addListener("bounds_changed", () => {
searchBox.setBounds(map.getBounds());
});
////"bound_changed"The event is(Fired when there is a change in the map / viewport of the visible range)
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Map/bounds_changed/
////"getBounds"The method gets the viewport boundaries. Map class method.
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Map/getBounds/
let markers = [];
searchBox.addListener("places_changed", () => {
////"place_chaged"The event is an event of the AutoComplete class.
////https://developers.google.com/maps/documentation/javascript/reference/places-widget#Autocomplete.place_changed
const places = searchBox.getPlaces();
////"getPlaces"Method is query(Search keyword)Array(PlaceResult)Return with.
////https://developers.google.com/maps/documentation/javascript/reference/places-widget#Autocomplete.place_changed
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach((marker) => {
//"forEach"The method is the key of the Map object to the function in the argument/Assign values in order and execute the function.
//Map object:
//https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Map
marker.setMap(null);
////The setMap method is Marker(Polyline,Circle etc.)Method of class. Place the Marker in the specified position. If the argument is null, it will be removed from the map.
});
markers = [];
// For each place, get the icon, name and location.
const bounds = new google.maps.LatLngBounds();
////"LatLngBounds"The class creates an instrument that creates boundaries. The arguments are the lower left and upper right coordinates.
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/LatLngBounds/#:~:text=LatLngBounds%E3%82%AF%E3%83%A9%E3%82%B9%E3%81%AF%E5%A2%83%E7%95%8C(Bounding,%E4%BD%9C%E3%82%8B%E3%81%93%E3%81%A8%E3%82%82%E3%81%A7%E3%81%8D%E3%81%BE%E3%81%99%E3%80%82
places.forEach((place) => {
if (!place.geometry) {
////"geometry"Is a method of the place library.
console.log("Returned place contains no geometry");
return;
}
const icon = {
url: place.icon,
////"icon"Is an object that represents an icon. When you want to make the marker an original image.
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Icon/
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
////"Point"A class is an instance method that determines the position of a marker label or the like.
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Point/
scaledSize: new google.maps.Size(25, 25),
};
// Create a marker for each place.
markers.push(
new google.maps.Marker({
map,
icon,
title: place.name,
position: place.geometry.location,
})
);
if (place.geometry.viewport) {
////viewport"Method
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
////"union"The method is a method of the LatLngBounds class. Incorporates the specified boundary into its own boundary and synthesizes it.
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/LatLngBounds/union/
} else {
bounds.extend(place.geometry.location);
////"extend"The method is a method of the LatLngBounds class. Add new position coordinates to your boundaries.
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/LatLngBounds/extend/
}
});
map.fitBounds(bounds);
////"fitBounds"The method is a method of the map class. Change the viewport to a position where you can easily see the specified boundary.
////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Map/fitBounds/#:~:text=Map.fitBounds()%E3%81%AFMap,%E5%A4%89%E6%9B%B4%E3%81%97%E3%81%A6%E3%81%8F%E3%82%8C%E3%81%BE%E3%81%99%E3%80%82
});
}
style.css
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
You should now see the map and search box.
Feel free to play with css to your liking.
If you write a constant or function with the same name separately, it will not work well. Please check in case of an error.
If you leave step 2, the search box will be in an unsophisticated position, so decorate the box.
of js file
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
The position of the search box has been placed in TOP_LEFT with.
Since javascript is loaded after reading css, It will be specified by overwriting the description of css.
Delete this line and decorate the id and class of the input tag with CSS as you like.
This site called [snazzy] [4] allows you to edit intuitively as you like. The style selected or edited here can copy JSON data, so you can edit the style as you like by pasting it into JS as it is.
Just playing with snazzy is fun, so please take a look. [4]:https://snazzymaps.com/editor/customize/21
By the way, the purple map style pasted at the beginning of the article is as follows.
input.js
const map = new google.maps.Map(document.getElementById("map"), opts);
var opts = {
zoom: 15,
center: { lat: -33.8688, lng: 151.2195 },
styles: [
//Hide all labels
{
featureType: 'all',
elementType: 'labels',
stylers: [
{visibility: 'off'},
],
},
{
featureType: 'transit',
elementType: 'labels',
stylers: [
{visibility: 'on'},
],
},
//poi=Redisplay only the "Sightseeing spots, facilities, etc." icon
{
featureType: 'poi',
elementType: 'labels.icon',
stylers: [
{visibility: 'inherit'},
],
},
//Customize the color of the entire map
//Unify the basic color to red+Desaturate
{
featureType: 'all',
elementType: 'all',
stylers: [
{hue: '#5f0285'},
{saturation : -50},
],
}
]
that's all. If it doesn't work, please follow the official documentation.
Recommended Posts