📅  最后修改于: 2023-12-03 15:15:24.359000             🧑  作者: Mango
Google Places API is a service that provides information about places using HTTP requests. With Google Places API, you can search for places, get details about a specific place, and more. In this online example, we will learn how to use Google Places API to search for places.
To use Google Places API, you need to obtain an API key from the Google Cloud Console. Follow these steps to get an API key:
Create an HTML page with a search box and a map. Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>Google Places API Online Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
</head>
<body>
<input id="search-box" type="text" placeholder="Search for places">
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.866, lng: 151.196},
zoom: 15
});
var searchBox = new google.maps.places.SearchBox(document.getElementById('search-box'));
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"></script>
</body>
</html>
Replace YOUR_API_KEY
with your API key obtained in Step 1.
In this online example, we learned how to use Google Places API to search for places. By using Google Places API, you can easily add location-based features to your web applications.