Google Place API
| google.maps.places.PlacesService;/ google.maps.palces.SearchBox; | google.maps.Map |
| google.maps.places.PlacesServiceStatus; | google.maps.Marker;/ google.maps.Animation.DROP; |
| google.maps.LatLngBounds; | google.maps.InfoWindow; |
| google.maps.DirectionStatus; | google.maps.Point; / google.maps.Size; |
| google.maps.places.Autocomplete;/google.maps.places.AutocompleteService; | google.maps.TravelMode |
| google.maps.DirectionsService; | google.maps.DirectionsRenderer; |
*Place searches:
| Nearby Search | returns a list of nearby places based on a user's location. |
| Text Search | returns a list of nearby places based on a search string, eg. "Pizza". |
| Radar Search | returns a large list of places within a specified search radius, but with less detail than either Nearby Search or Text Search. |
| Place Details Requests | return more detailed information about a specific place, including user reviews. |
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> var map; var infowindow; function initMap() { var pyrmont = {lat: -33.867, lng: 151.195}; map = new google.maps.Map(document.getElementById('map'), { center: pyrmont, zoom: 15 }); infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); service.nearbySearch({ location: pyrmont, radius: 500, type: ['store'] }, callback); } function callback(results, status) { if (status === google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { createMarker(results[i]); } } } function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(place.name); infowindow.open(map, this); }); }
*Place details
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: -33.866, lng: 151.196}, zoom: 15 }); var infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); service.getDetails({ placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4' }, function(place, status) { //callback place is google.maps.places.PlaceResult; statusis google.maps.places.PlacesServiceStatus if (status === google.maps.places.PlacesServiceStatus.OK) { var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + 'Place ID: ' + place.place_id + '<br>' + place.formatted_address + '</div>'); infowindow.open(map, this); }); } }); }
*Place search pagination(分页): accessing additional results, By default, each place search returns up to 20 results per query. However, each search can return as many as 60 results; PlaceSearchPagination; hasNextPage; nextPage()
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> var map; function initMap() { var pyrmont = {lat: -33.866, lng: 151.196}; map = new google.maps.Map(document.getElementById('map'), { center: pyrmont, zoom: 17 }); var service = new google.maps.places.PlacesService(map); service.nearbySearch({ location: pyrmont, radius: 500, type: ['store'] }, processResults); } function processResults(results, status, pagination) { if (status !== google.maps.places.PlacesServiceStatus.OK) { return; } else { createMarkers(results); if (pagination.hasNextPage) { var moreButton = document.getElementById('more'); moreButton.disabled = false; moreButton.addEventListener('click', function() { moreButton.disabled = true; pagination.nextPage(); }); } } } function createMarkers(places) { var bounds = new google.maps.LatLngBounds(); var placesList = document.getElementById('places'); for (var i = 0, place; place = places[i]; i++) { var image = { 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) }; var marker = new google.maps.Marker({ map: map, icon: image, title: place.name, position: place.geometry.location }); placesList.innerHTML += '<li>' + place.name + '</li>'; bounds.extend(place.geometry.location); } map.fitBounds(bounds); }
*Search for up to 200 places with Radar Search:The Radar Search returns more results than a Nearby Search or Text Search, but the results contain fewer fields. You can callPlacesService.getDetails() to get more information about any of the places in the response.
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> var map; var infoWindow; var service; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -33.867, lng: 151.206}, zoom: 15, styles: [{ stylers: [{ visibility: 'simplified' }] }, { elementType: 'labels', stylers: [{ visibility: 'off' }] }] }); infoWindow = new google.maps.InfoWindow(); service = new google.maps.places.PlacesService(map); // The idle event is a debounced event, so we can query & listen without // throwing too many requests at the server. map.addListener('idle', performSearch); } function performSearch() { var request = { bounds: map.getBounds(), keyword: 'best view' }; service.radarSearch(request, callback); } function callback(results, status) { if (status !== google.maps.places.PlacesServiceStatus.OK) { console.error(status); return; } for (var i = 0, result; result = results[i]; i++) { addMarker(result); } } function addMarker(place) { var marker = new google.maps.Marker({ map: map, position: place.geometry.location, icon: { url: 'http://maps.gstatic.com/mapfiles/circle.png', anchor: new google.maps.Point(10, 10), scaledSize: new google.maps.Size(10, 17) } }); google.maps.event.addListener(marker, 'click', function() { service.getDetails(place, function(result, status) { if (status !== google.maps.places.PlacesServiceStatus.OK) { console.error(status); return; } infoWindow.setContent(result.name); infoWindow.open(map, marker); }); }); }
*Place Autocomplete
<!DOCTYPE html> <html> <head> <title>Place Autocomplete</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } .controls { margin-top: 10px; border: 1px solid transparent; border-radius: 2px 0 0 2px; box-sizing: border-box; -moz-box-sizing: border-box; height: 32px; outline: none; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); } #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: 300px; } #pac-input:focus { border-color: #4d90fe; } .pac-container { font-family: Roboto; } #type-selector { color: #fff; background-color: #4d90fe; padding: 5px 11px 0px 11px; } #type-selector label { font-family: Roboto; font-size: 13px; font-weight: 300; } </style> </head> <body> <input id="pac-input" class="controls" type="text" placeholder="Enter a location"> <div id="type-selector" class="controls"> <input type="radio" name="type" id="changetype-all" checked="checked"> <label for="changetype-all">All</label> <input type="radio" name="type" id="changetype-establishment"> <label for="changetype-establishment">Establishments</label> <input type="radio" name="type" id="changetype-address"> <label for="changetype-address">Addresses</label> <input type="radio" name="type" id="changetype-geocode"> <label for="changetype-geocode">Geocodes</label> </div> <div id="map"></div> <script> // This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: -33.8688, lng: 151.2195}, zoom: 13 }); var input = /** @type {!HTMLInputElement} */( document.getElementById('pac-input')); var types = document.getElementById('type-selector'); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(types); var autocomplete = new google.maps.places.Autocomplete(input); autocomplete.bindTo('bounds', map); var infowindow = new google.maps.InfoWindow(); var marker = new google.maps.Marker({ map: map, anchorPoint: new google.maps.Point(0, -29) }); autocomplete.addListener('place_changed', function() { infowindow.close(); marker.setVisible(false); var place = autocomplete.getPlace(); if (!place.geometry) { window.alert("Autocomplete's returned place contains no geometry"); return; } // If the place has a geometry, then present it on a map. if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(17); // Why 17? Because it looks good. } marker.setIcon(/** @type {google.maps.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(35, 35) })); marker.setPosition(place.geometry.location); marker.setVisible(true); var address = ''; if (place.address_components) { address = [ (place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '') ].join(' '); } infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address); infowindow.open(map, marker); }); // Sets a listener on a radio button to change the filter type on Places // Autocomplete. function setupClickListener(id, types) { var radioButton = document.getElementById(id); radioButton.addEventListener('click', function() { autocomplete.setTypes(types); }); } setupClickListener('changetype-all', []); setupClickListener('changetype-address', ['address']); setupClickListener('changetype-establishment', ['establishment']); setupClickListener('changetype-geocode', ['geocode']); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script> </body> </html>

*Autocomplete address form
<!DOCTYPE html> <html> <head> <title>Place Autocomplete Address Form</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } </style> <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"> <style> #locationField, #controls { position: relative; width: 480px; } #autocomplete { position: absolute; top: 0px; left: 0px; width: 99%; } .label { text-align: right; font-weight: bold; width: 100px; color: #303030; } #address { border: 1px solid #000090; background-color: #f0f0ff; width: 480px; padding-right: 2px; } #address td { font-size: 10pt; } .field { width: 99%; } .slimField { width: 80px; } .wideField { width: 200px; } #locationField { height: 20px; margin-bottom: 2px; } </style> </head> <body> <div id="locationField"> <input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input> </div> <table id="address"> <tr> <td class="label">Street address</td> <td class="slimField"><input class="field" id="street_number" disabled="true"></input></td> <td class="wideField" colspan="2"><input class="field" id="route" disabled="true"></input></td> </tr> <tr> <td class="label">City</td> <td class="wideField" colspan="3"><input class="field" id="locality" disabled="true"></input></td> </tr> <tr> <td class="label">State</td> <td class="slimField"><input class="field" id="administrative_area_level_1" disabled="true"></input></td> <td class="label">Zip code</td> <td class="wideField"><input class="field" id="postal_code" disabled="true"></input></td> </tr> <tr> <td class="label">Country</td> <td class="wideField" colspan="3"><input class="field" id="country" disabled="true"></input></td> </tr> </table> <script> // This example displays an address form, using the autocomplete feature // of the Google Places API to help users fill in the information. // This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> var placeSearch, autocomplete; var componentForm = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' }; function initAutocomplete() { // Create the autocomplete object, restricting the search to geographical // location types. autocomplete = new google.maps.places.Autocomplete( /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')), {types: ['geocode']}); // When the user selects an address from the dropdown, populate the address // fields in the form. autocomplete.addListener('place_changed', fillInAddress); } function fillInAddress() { // Get the place details from the autocomplete object. var place = autocomplete.getPlace(); for (var component in componentForm) { document.getElementById(component).value = ''; document.getElementById(component).disabled = false; } // Get each component of the address from the place details // and fill the corresponding field on the form. for (var i = 0; i < place.address_components.length; i++) { var addressType = place.address_components[i].types[0]; if (componentForm[addressType]) { var val = place.address_components[i][componentForm[addressType]]; document.getElementById(addressType).value = val; } } } // Bias the autocomplete object to the user's geographical location, // as supplied by the browser's 'navigator.geolocation' object. function geolocate() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var geolocation = { lat: position.coords.latitude, lng: position.coords.longitude }; var circle = new google.maps.Circle({ center: geolocation, radius: position.coords.accuracy }); autocomplete.setBounds(circle.getBounds()); }); } } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete" async defer></script> </body> </html>

*Autocomplete hotel search
var map, places, infoWindow; var markers = []; var autocomplete; var countryRestrict = {'country': 'us'}; var MARKER_PATH = 'https://maps.gstatic.com/intl/en_us/mapfiles/marker_green'; var hostnameRegexp = new RegExp('^https?://.+?/'); var countries = { 'au': { center: {lat: -25.3, lng: 133.8}, zoom: 4 }, 'br': { center: {lat: -14.2, lng: -51.9}, zoom: 3 }, 'ca': { center: {lat: 62, lng: -110.0}, zoom: 3 }, 'fr': { center: {lat: 46.2, lng: 2.2}, zoom: 5 }, 'de': { center: {lat: 51.2, lng: 10.4}, zoom: 5 }, 'mx': { center: {lat: 23.6, lng: -102.5}, zoom: 4 }, 'nz': { center: {lat: -40.9, lng: 174.9}, zoom: 5 }, 'it': { center: {lat: 41.9, lng: 12.6}, zoom: 5 }, 'za': { center: {lat: -30.6, lng: 22.9}, zoom: 5 }, 'es': { center: {lat: 40.5, lng: -3.7}, zoom: 5 }, 'pt': { center: {lat: 39.4, lng: -8.2}, zoom: 6 }, 'us': { center: {lat: 37.1, lng: -95.7}, zoom: 3 }, 'uk': { center: {lat: 54.8, lng: -4.6}, zoom: 5 } }; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: countries['us'].zoom, center: countries['us'].center, mapTypeControl: false, panControl: false, zoomControl: false, streetViewControl: false }); infoWindow = new google.maps.InfoWindow({ content: document.getElementById('info-content') }); // Create the autocomplete object and associate it with the UI input control. // Restrict the search to the default country, and to place type "cities". autocomplete = new google.maps.places.Autocomplete( /** @type {!HTMLInputElement} */ ( document.getElementById('autocomplete')), { types: ['(cities)'], componentRestrictions: countryRestrict }); places = new google.maps.places.PlacesService(map); autocomplete.addListener('place_changed', onPlaceChanged); // Add a DOM event listener to react when the user selects a country. document.getElementById('country').addEventListener( 'change', setAutocompleteCountry); } // When the user selects a city, get the place details for the city and // zoom the map in on the city. function onPlaceChanged() { var place = autocomplete.getPlace(); if (place.geometry) { map.panTo(place.geometry.location); map.setZoom(15); search(); } else { document.getElementById('autocomplete').placeholder = 'Enter a city'; } } // Search for hotels in the selected city, within the viewport of the map. function search() { var search = { bounds: map.getBounds(), types: ['lodging'] }; places.nearbySearch(search, function(results, status) { if (status === google.maps.places.PlacesServiceStatus.OK) { clearResults(); clearMarkers(); // Create a marker for each hotel found, and // assign a letter of the alphabetic to each marker icon. for (var i = 0; i < results.length; i++) { var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i); var markerIcon = MARKER_PATH + markerLetter + '.png'; // Use marker animation to drop the icons incrementally on the map. markers[i] = new google.maps.Marker({ position: results[i].geometry.location, animation: google.maps.Animation.DROP, icon: markerIcon }); // If the user clicks a hotel marker, show the details of that hotel // in an info window. markers[i].placeResult = results[i]; google.maps.event.addListener(markers[i], 'click', showInfoWindow); setTimeout(dropMarker(i), i * 100); addResult(results[i], i); } } }); } function clearMarkers() { for (var i = 0; i < markers.length; i++) { if (markers[i]) { markers[i].setMap(null); } } markers = []; } // Set the country restriction based on user input. // Also center and zoom the map on the given country. function setAutocompleteCountry() { var country = document.getElementById('country').value; if (country == 'all') { autocomplete.setComponentRestrictions([]); map.setCenter({lat: 15, lng: 0}); map.setZoom(2); } else { autocomplete.setComponentRestrictions({'country': country}); map.setCenter(countries[country].center); map.setZoom(countries[country].zoom); } clearResults(); clearMarkers(); } function dropMarker(i) { return function() { markers[i].setMap(map); }; } function addResult(result, i) { var results = document.getElementById('results'); var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i); var markerIcon = MARKER_PATH + markerLetter + '.png'; var tr = document.createElement('tr'); tr.style.backgroundColor = (i % 2 === 0 ? '#F0F0F0' : '#FFFFFF'); tr.onclick = function() { google.maps.event.trigger(markers[i], 'click'); }; var iconTd = document.createElement('td'); var nameTd = document.createElement('td'); var icon = document.createElement('img'); icon.src = markerIcon; icon.setAttribute('class', 'placeIcon'); icon.setAttribute('className', 'placeIcon'); var name = document.createTextNode(result.name); iconTd.appendChild(icon); nameTd.appendChild(name); tr.appendChild(iconTd); tr.appendChild(nameTd); results.appendChild(tr); } function clearResults() { var results = document.getElementById('results'); while (results.childNodes[0]) { results.removeChild(results.childNodes[0]); } } // Get the place details for a hotel. Show the information in an info window, // anchored on the marker for the hotel that the user selected. function showInfoWindow() { var marker = this; places.getDetails({placeId: marker.placeResult.place_id}, function(place, status) { if (status !== google.maps.places.PlacesServiceStatus.OK) { return; } infoWindow.open(map, marker); buildIWContent(place); }); } // Load the place information into the HTML elements used by the info window. function buildIWContent(place) { document.getElementById('iw-icon').innerHTML = '<img class="hotelIcon" ' + 'src="' + place.icon + '"/>'; document.getElementById('iw-url').innerHTML = '<b><a href="' + place.url + '">' + place.name + '</a></b>'; document.getElementById('iw-address').textContent = place.vicinity; if (place.formatted_phone_number) { document.getElementById('iw-phone-row').style.display = ''; document.getElementById('iw-phone').textContent = place.formatted_phone_number; } else { document.getElementById('iw-phone-row').style.display = 'none'; } // Assign a five-star rating to the hotel, using a black star ('✭') // to indicate the rating the hotel has earned, and a white star ('✩') // for the rating points not achieved. if (place.rating) { var ratingHtml = ''; for (var i = 0; i < 5; i++) { if (place.rating < (i + 0.5)) { ratingHtml += '✩'; } else { ratingHtml += '✭'; } document.getElementById('iw-rating-row').style.display = ''; document.getElementById('iw-rating').innerHTML = ratingHtml; } } else { document.getElementById('iw-rating-row').style.display = 'none'; } // The regexp isolates the first part of the URL (domain plus subdomain) // to give a short URL for displaying in the info window. if (place.website) { var fullUrl = place.website; var website = hostnameRegexp.exec(place.website); if (website === null) { website = 'http://' + place.website + '/'; fullUrl = website; } document.getElementById('iw-website-row').style.display = ''; document.getElementById('iw-website').textContent = website; } else { document.getElementById('iw-website-row').style.display = 'none'; } }
Full Code:
<!DOCTYPE html> <html> <head> <title>Place Autocomplete Hotel Search</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } table { font-size: 12px; } #map { width: 440px; } #listing { position: absolute; width: 200px; height: 470px; overflow: auto; left: 442px; top: 0px; cursor: pointer; overflow-x: hidden; } #findhotels { position: absolute; text-align: right; width: 100px; font-size: 14px; padding: 4px; z-index: 5; background-color: #fff; } #locationField { position: absolute; width: 190px; height: 25px; left: 108px; top: 0px; z-index: 5; background-color: #fff; } #controls { position: absolute; left: 300px; width: 140px; top: 0px; z-index: 5; background-color: #fff; } #autocomplete { width: 100%; } #country { width: 100%; } .placeIcon { width: 20px; height: 34px; margin: 4px; } .hotelIcon { width: 24px; height: 24px; } #resultsTable { border-collapse: collapse; width: 240px; } #rating { font-size: 13px; font-family: Arial Unicode MS; } .iw_table_row { height: 18px; } .iw_attribute_name { font-weight: bold; text-align: right; } .iw_table_icon { text-align: right; } </style> </head> <body> <div id="findhotels"> Find hotels in: </div> <div id="locationField"> <input id="autocomplete" placeholder="Enter a city" type="text" /> </div> <div id="controls"> <select id="country"> <option value="all">All</option> <option value="au">Australia</option> <option value="br">Brazil</option> <option value="ca">Canada</option> <option value="fr">France</option> <option value="de">Germany</option> <option value="mx">Mexico</option> <option value="nz">New Zealand</option> <option value="it">Italy</option> <option value="za">South Africa</option> <option value="es">Spain</option> <option value="pt">Portugal</option> <option value="us" selected>U.S.A.</option> <option value="uk">United Kingdom</option> </select> </div> <div id="map"></div> <div id="listing"> <table id="resultsTable"> <tbody id="results"></tbody> </table> </div> <div style="display: none"> <div id="info-content"> <table> <tr id="iw-url-row" class="iw_table_row"> <td id="iw-icon" class="iw_table_icon"></td> <td id="iw-url"></td> </tr> <tr id="iw-address-row" class="iw_table_row"> <td class="iw_attribute_name">Address:</td> <td id="iw-address"></td> </tr> <tr id="iw-phone-row" class="iw_table_row"> <td class="iw_attribute_name">Telephone:</td> <td id="iw-phone"></td> </tr> <tr id="iw-rating-row" class="iw_table_row"> <td class="iw_attribute_name">Rating:</td> <td id="iw-rating"></td> </tr> <tr id="iw-website-row" class="iw_table_row"> <td class="iw_attribute_name">Website:</td> <td id="iw-website"></td> </tr> </table> </div> </div> <script> // This example uses the autocomplete feature of the Google Places API. // It allows the user to find all hotels in a given place, within a given // country. It then displays markers for all the hotels returned, // with on-click details for each hotel. // This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> var map, places, infoWindow; var markers = []; var autocomplete; var countryRestrict = {'country': 'us'}; var MARKER_PATH = 'https://maps.gstatic.com/intl/en_us/mapfiles/marker_green'; var hostnameRegexp = new RegExp('^https?://.+?/'); var countries = { 'au': { center: {lat: -25.3, lng: 133.8}, zoom: 4 }, 'br': { center: {lat: -14.2, lng: -51.9}, zoom: 3 }, 'ca': { center: {lat: 62, lng: -110.0}, zoom: 3 }, 'fr': { center: {lat: 46.2, lng: 2.2}, zoom: 5 }, 'de': { center: {lat: 51.2, lng: 10.4}, zoom: 5 }, 'mx': { center: {lat: 23.6, lng: -102.5}, zoom: 4 }, 'nz': { center: {lat: -40.9, lng: 174.9}, zoom: 5 }, 'it': { center: {lat: 41.9, lng: 12.6}, zoom: 5 }, 'za': { center: {lat: -30.6, lng: 22.9}, zoom: 5 }, 'es': { center: {lat: 40.5, lng: -3.7}, zoom: 5 }, 'pt': { center: {lat: 39.4, lng: -8.2}, zoom: 6 }, 'us': { center: {lat: 37.1, lng: -95.7}, zoom: 3 }, 'uk': { center: {lat: 54.8, lng: -4.6}, zoom: 5 } }; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: countries['us'].zoom, center: countries['us'].center, mapTypeControl: false, panControl: false, zoomControl: false, streetViewControl: false }); infoWindow = new google.maps.InfoWindow({ content: document.getElementById('info-content') }); // Create the autocomplete object and associate it with the UI input control. // Restrict the search to the default country, and to place type "cities". autocomplete = new google.maps.places.Autocomplete( /** @type {!HTMLInputElement} */ ( document.getElementById('autocomplete')), { types: ['(cities)'], componentRestrictions: countryRestrict }); places = new google.maps.places.PlacesService(map); autocomplete.addListener('place_changed', onPlaceChanged); // Add a DOM event listener to react when the user selects a country. document.getElementById('country').addEventListener( 'change', setAutocompleteCountry); } // When the user selects a city, get the place details for the city and // zoom the map in on the city. function onPlaceChanged() { var place = autocomplete.getPlace(); if (place.geometry) { map.panTo(place.geometry.location); map.setZoom(15); search(); } else { document.getElementById('autocomplete').placeholder = 'Enter a city'; } } // Search for hotels in the selected city, within the viewport of the map. function search() { var search = { bounds: map.getBounds(), types: ['lodging'] }; places.nearbySearch(search, function(results, status) { if (status === google.maps.places.PlacesServiceStatus.OK) { clearResults(); clearMarkers(); // Create a marker for each hotel found, and // assign a letter of the alphabetic to each marker icon. for (var i = 0; i < results.length; i++) { var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i); var markerIcon = MARKER_PATH + markerLetter + '.png'; // Use marker animation to drop the icons incrementally on the map. markers[i] = new google.maps.Marker({ position: results[i].geometry.location, animation: google.maps.Animation.DROP, icon: markerIcon }); // If the user clicks a hotel marker, show the details of that hotel // in an info window. markers[i].placeResult = results[i]; google.maps.event.addListener(markers[i], 'click', showInfoWindow); setTimeout(dropMarker(i), i * 100); addResult(results[i], i); } } }); } function clearMarkers() { for (var i = 0; i < markers.length; i++) { if (markers[i]) { markers[i].setMap(null); } } markers = []; } // Set the country restriction based on user input. // Also center and zoom the map on the given country. function setAutocompleteCountry() { var country = document.getElementById('country').value; if (country == 'all') { autocomplete.setComponentRestrictions([]); map.setCenter({lat: 15, lng: 0}); map.setZoom(2); } else { autocomplete.setComponentRestrictions({'country': country}); map.setCenter(countries[country].center); map.setZoom(countries[country].zoom); } clearResults(); clearMarkers(); } function dropMarker(i) { return function() { markers[i].setMap(map); }; } function addResult(result, i) { var results = document.getElementById('results'); var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i); var markerIcon = MARKER_PATH + markerLetter + '.png'; var tr = document.createElement('tr'); tr.style.backgroundColor = (i % 2 === 0 ? '#F0F0F0' : '#FFFFFF'); tr.onclick = function() { google.maps.event.trigger(markers[i], 'click'); }; var iconTd = document.createElement('td'); var nameTd = document.createElement('td'); var icon = document.createElement('img'); icon.src = markerIcon; icon.setAttribute('class', 'placeIcon'); icon.setAttribute('className', 'placeIcon'); var name = document.createTextNode(result.name); iconTd.appendChild(icon); nameTd.appendChild(name); tr.appendChild(iconTd); tr.appendChild(nameTd); results.appendChild(tr); } function clearResults() { var results = document.getElementById('results'); while (results.childNodes[0]) { results.removeChild(results.childNodes[0]); } } // Get the place details for a hotel. Show the information in an info window, // anchored on the marker for the hotel that the user selected. function showInfoWindow() { var marker = this; places.getDetails({placeId: marker.placeResult.place_id}, function(place, status) { if (status !== google.maps.places.PlacesServiceStatus.OK) { return; } infoWindow.open(map, marker); buildIWContent(place); }); } // Load the place information into the HTML elements used by the info window. function buildIWContent(place) { document.getElementById('iw-icon').innerHTML = '<img class="hotelIcon" ' + 'src="' + place.icon + '"/>'; document.getElementById('iw-url').innerHTML = '<b><a href="' + place.url + '">' + place.name + '</a></b>'; document.getElementById('iw-address').textContent = place.vicinity; if (place.formatted_phone_number) { document.getElementById('iw-phone-row').style.display = ''; document.getElementById('iw-phone').textContent = place.formatted_phone_number; } else { document.getElementById('iw-phone-row').style.display = 'none'; } // Assign a five-star rating to the hotel, using a black star ('✭') // to indicate the rating the hotel has earned, and a white star ('✩') // for the rating points not achieved. if (place.rating) { var ratingHtml = ''; for (var i = 0; i < 5; i++) { if (place.rating < (i + 0.5)) { ratingHtml += '✩'; } else { ratingHtml += '✭'; } document.getElementById('iw-rating-row').style.display = ''; document.getElementById('iw-rating').innerHTML = ratingHtml; } } else { document.getElementById('iw-rating-row').style.display = 'none'; } // The regexp isolates the first part of the URL (domain plus subdomain) // to give a short URL for displaying in the info window. if (place.website) { var fullUrl = place.website; var website = hostnameRegexp.exec(place.website); if (website === null) { website = 'http://' + place.website + '/'; fullUrl = website; } document.getElementById('iw-website-row').style.display = ''; document.getElementById('iw-website').textContent = website; } else { document.getElementById('iw-website-row').style.display = 'none'; } } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script> </body> </html>
*Places search box
function initAutocomplete() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: -33.8688, lng: 151.2195}, zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); // Create the search box and link it to the UI element. var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.SearchBox(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); // Bias the SearchBox results towards current map's viewport. map.addListener('bounds_changed', function() { searchBox.setBounds(map.getBounds()); }); var markers = []; // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener('places_changed', function() { var places = searchBox.getPlaces(); if (places.length == 0) { return; } // Clear out the old markers. markers.forEach(function(marker) { marker.setMap(null); }); markers = []; // For each place, get the icon, name and location. var bounds = new google.maps.LatLngBounds(); places.forEach(function(place) { 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) }; // Create a marker for each place. markers.push(new google.maps.Marker({ map: map, icon: icon, title: place.name, position: place.geometry.location })); if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); }); }

*Retrieving autocomplete predictions
*Place ID finder
function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: -33.8688, lng: 151.2195}, zoom: 13 }); var input = document.getElementById('pac-input'); var autocomplete = new google.maps.places.Autocomplete(input); autocomplete.bindTo('bounds', map); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); var infowindow = new google.maps.InfoWindow(); var marker = new google.maps.Marker({ map: map }); marker.addListener('click', function() { infowindow.open(map, marker); }); autocomplete.addListener('place_changed', function() { infowindow.close(); var place = autocomplete.getPlace(); if (!place.geometry) { return; } if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(17); } // Set the position of the marker using the place ID and location. marker.setPlace({ placeId: place.place_id, location: place.geometry.location }); marker.setVisible(true); infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + 'Place ID: ' + place.place_id + '<br>' + place.formatted_address); infowindow.open(map, marker); }); }
*Place Autocomplete and Directions
function initMap() { var origin_place_id = null; var destination_place_id = null; var travel_mode = google.maps.TravelMode.WALKING; var map = new google.maps.Map(document.getElementById('map'), { mapTypeControl: false, center: {lat: -33.8688, lng: 151.2195}, zoom: 13 }); var directionsService = new google.maps.DirectionsService; var directionsDisplay = new google.maps.DirectionsRenderer; directionsDisplay.setMap(map); var origin_input = document.getElementById('origin-input'); var destination_input = document.getElementById('destination-input'); var modes = document.getElementById('mode-selector'); map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(modes); var origin_autocomplete = new google.maps.places.Autocomplete(origin_input); origin_autocomplete.bindTo('bounds', map); var destination_autocomplete = new google.maps.places.Autocomplete(destination_input); destination_autocomplete.bindTo('bounds', map); // Sets a listener on a radio button to change the filter type on Places // Autocomplete. function setupClickListener(id, mode) { var radioButton = document.getElementById(id); radioButton.addEventListener('click', function() { travel_mode = mode; }); } setupClickListener('changemode-walking', google.maps.TravelMode.WALKING); setupClickListener('changemode-transit', google.maps.TravelMode.TRANSIT); setupClickListener('changemode-driving', google.maps.TravelMode.DRIVING); function expandViewportToFitPlace(map, place) { if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(17); } } origin_autocomplete.addListener('place_changed', function() { var place = origin_autocomplete.getPlace(); if (!place.geometry) { window.alert("Autocomplete's returned place contains no geometry"); return; } expandViewportToFitPlace(map, place); // If the place has a geometry, store its place ID and route if we have // the other place ID origin_place_id = place.place_id; route(origin_place_id, destination_place_id, travel_mode, directionsService, directionsDisplay); }); destination_autocomplete.addListener('place_changed', function() { var place = destination_autocomplete.getPlace(); if (!place.geometry) { window.alert("Autocomplete's returned place contains no geometry"); return; } expandViewportToFitPlace(map, place); // If the place has a geometry, store its place ID and route if we have // the other place ID destination_place_id = place.place_id; route(origin_place_id, destination_place_id, travel_mode, directionsService, directionsDisplay); }); function route(origin_place_id, destination_place_id, travel_mode, directionsService, directionsDisplay) { if (!origin_place_id || !destination_place_id) { return; } directionsService.route({ origin: {'placeId': origin_place_id}, destination: {'placeId': destination_place_id}, travelMode: travel_mode }, function(response, status) { if (status === google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } else { window.alert('Directions request failed due to ' + status); } }); } }

浙公网安备 33010602011771号