Alright, let's get you set up with the Google Maps JavaScript API! It's pretty neat for embedding interactive maps right into your website.
First things first, you'll need an API key. It's free to get started, but it's how Google tracks usage. Head over to the
Once you've got your API key, you can drop this basic HTML structure into your webpage:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
<script>
let map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 34.6937, lng: 136.5022}, // Example: Toin, Mie, Japan
zoom: 12
});
}
</script>
</body>
</html>
Here's the breakdown of what's happening:
<!DOCTYPE html>
and basic HTML structure: This is just your standard webpage setup.<div id="map"></div>
: This is the empty container where the map will be rendered. The CSS in the<style>
tag just gives it a basic height and width so you can see it.<script async defer src="...">
: This is the crucial part where you load the Google Maps JavaScript API.https://maps.googleapis.com/maps/api/js
: This is the API endpoint.?key=YOUR_API_KEY
: ReplaceYOUR_API_KEY
with the actual API key you got from the Google Cloud Console!&callback=initMap
: This tells the API to call theinitMap
JavaScript function once the API has finished loading.async defer
: These attributes help the page load faster by downloading the script without blocking the rendering of the HTML.
<script>
block: This is where your JavaScript code lives.let map;
: This declares a variable to hold your map instance.function initMap() { ... }
: This function is called by the API after it loads.map = new google.maps.Map(document.getElementById('map'), { ... });
: This creates a new Google Map object.document.getElementById('map')
: This tells the API where to put the map (inside thediv
with the ID "map").{ center: {lat: 34.6937, lng: 136.5022}, zoom: 12 }
: This is an object containing the map options.center
: An object withlat
(latitude) andlng
(longitude) properties defining the initial center point of the map. I've put in the approximate coordinates for Toin, Mie, Japan! Feel free to change these.zoom
: An integer specifying the initial zoom level of the map (higher number means more zoomed in).
Just save this code as an HTML file (like index.html
), replace "YOUR_API_KEY"
with your actual key, and open it in your web browser. You should see a map centered around Toin!
From here, you can explore tons of other features the API offers, like adding markers, drawing shapes, displaying info windows, and much more. The
Let me know if you want to try adding a marker or explore any other specific functionality!
0 件のコメント:
コメントを投稿