Google 地图 API 使用下拉菜单(select 选项)根据城市搜索地点无效
Google Maps API searching for places based on city using dropdown (select option) not working
你好我想问一下google地图API。以前,我是使用 Google 地图 API 的初学者。我想使用 select option
.
按城市搜索地点
我试过在 youtube 上阅读文档和一些视频,在 Whosebug 上阅读其他帖子,但 none 其中符合我的要求。
我想制作如下图。当我按 select option
搜索时,将出现所选城市。当我点击标记时,我会看到地点描述,例如照片、地名和描述。
我可以制作这样的功能吗?我真的坚持我所做的,我已经制作了一些代码,如下所示。请帮助我,我真的需要你的帮助。
let map;
let places;
let infoWindow;
let markers = [];
let autocomplete;
const countryRestrict = {
country: "tangerang"
};
const MARKER_PATH = "https://developers.google.com/maps/documentation/javascript/images/marker_green";
const hostnameRegexp = new RegExp("^https?://.+?/");
const cities = {
jakarta: {
center: {
lat: -6.186286,
lng: 106.822746
},
zoom: 12
},
tangerang: {
center: {
lat: -6.336135,
lng: 106.676924
},
zoom: 11
}
};
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: cities["tangerang"].zoom,
center: cities["tangerang"].center,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false,
fullscreenControl: false,
});
infoWindow = new google.maps.InfoWindow({
content: document.getElementById("info-content")
});
autocomplete = new google.maps.places.Autocomplete(
document.getElementById("autocomplete"), {
types: ["(cities)"],
componentRestrictions: countryRestrict
}
);
places = new google.maps.places.PlacesService(map);
autocomplete.addListener("place_changed", onPlaceChanged);
document.getElementById("country").addEventListener("change", setAutocompleteCountry);
}
function setAutocompleteCountry() {
const country = document.getElementById("country").value;
if (country == "all") {
autocomplete.setComponentRestrictions({
country: []
});
map.setCenter({
lat: 15,
lng: 0
});
map.setZoom(2);
} else {
autocomplete.setComponentRestrictions({
country: country
});
map.setCenter(cities[country].center);
map.setZoom(cities[country].zoom);
}
}
#mapsContent {
position: relative;
}
#mapsContent #controls {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
position: absolute;
left: 50%;
top: 5%;
-webkit-transform: translate(-50%, -5%);
transform: translate(-50%, -5%);
background-color: #fff;
padding: 10px 30px;
border-radius: 10px;
z-index: 9;
}
#mapsContent #controls .city {
padding-right: 30px;
border-right: 1px solid #acacac;
margin-right: 20px;
}
#contactContent #mapsContent #controls h4 {
color: #16215C;
font-size: 13px;
margin: 0;
}
#contactContent #mapsContent #controls #country {
border: none;
cursor: pointer;
}
#map {
position: relative;
width: 100%;
height: 900px;
background-color: #CACACA;
border-radius: 10px;
z-index: 0;
}
<div class="container-fluid">
<div class="row" id="mapsContent">
<div id="controls">
<div class="city">
<h4>Kota</h4>
</div>
<select id="country">
<option value="all">All</option>
<option value="jakarta">DKI Jakarta</option>
<option value="tangerang" selected>Tangerang</option>
</select>
</div>
<div id="map"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places&v=weekly" async defer></script>
为了获得您想要的结果,您将不得不使用 Place Details and Place photo 请求。如前所述,选择城市后,您已知的公司地点将显示标记和信息窗口,显示该地点的详细信息和初始照片。
每个城市的地点都在一个 JSON 对象中,但是,它只有每个唯一的地点 ID。修改JSON对象时,可以利用google
的place id finder inputting your company address to get the place's unique place_id. It is alright to cache the place ID as indicated in the service specific terms
为了进一步降低成本,您会看到我将 fields
参数指定为仅获取您需要的数据。您可以检查所有可用字段 here.
这是供您参考的 JSFiddle 示例:https://jsfiddle.net/pintsik999/0vjbep7h/
您还可以查看下面的代码:
"use strict";
let map;
let cities;
let markers = [];
var citiesObj = {
"cities": [{
"key": "DKI Jakarta",
"value": {
"city": "jakarta",
"center": {
"lat": -6.186286,
"lng": 106.822746
},
"zoom": 12,
//Since you know at least the address of the places, you can go here to get the unique place ID: https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder
"places": [{
"place_id": "ChIJB9Y8liH0aS4RemVuMOm5PFA"
},
{
"place_id": "ChIJA7dLFoL2aS4Rbu2LGxzIbAA"
}
]
}
}, {
"key": "Tangerang",
"value": {
"city": "tangerang",
"center": {
"lat": -6.336135,
"lng": 106.676924
},
"zoom": 11,
"places": [{
"place_id": "ChIJS3fhJPzkaS4RF8UTWV8LnLY"
}]
}
}]
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: -6.336135,
lng: 106.676924,
},
zoom: 10,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false,
fullscreenControl: false,
});
cities = document.getElementById("city");
cities.options.add(new Option('Select City', ''))
//value of cities are JSON objects to customize center and zoom of the map upon selection
for (var i = 0; i < citiesObj.cities.length; i++) {
cities.options.add(new Option(citiesObj.cities[i].key, JSON.stringify(citiesObj.cities[i].value)))
}
}
//add markers and infowindows on the places in the selected city
function cityChanged() {
//Hide/reset markers when city selection has changed.
deleteMarkers();
var selectedCity = JSON.parse(cities.value);
map.setCenter(new google.maps.LatLng(selectedCity.center));
//instantiate placedetail service
const service = new google.maps.places.PlacesService(map);
for (var i = 0; i < selectedCity.places.length; i++) {
const request = {
placeId: selectedCity.places[i].place_id,
//adding the fields parameter will allow you to specify the details that you only need so that you wont be billed unnecessarily for extra data that you don't use. Check all the available fields here: https://developers.google.com/maps/documentation/javascript/place-data-fields
fields: ["name", "formatted_address", "place_id", "geometry", "photos"],
};
service.getDetails(request, (place, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
addMarker(place);
}
});
}
}
function addMarker(place) {
var marker = new google.maps.Marker({
position: place.geometry.location,
map: map
});
addInfoWindow(marker, place);
markers.push(marker);
}
function addInfoWindow(marker, place) {
const infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(
"<img src='" + place.photos[0].getUrl() + " width='300' height='400'>" +
"<div><strong>" +
place.name +
"</strong><br>" +
"Place ID: " +
place.place_id +
"<br>" +
place.formatted_address +
"</div>"
);
infowindow.open(map, this);
});
}
function deleteMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
/* 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;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- REPLACE API KEY PLACEHOLDER -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div>
City:
<select id="city" onchange="cityChanged()">
</select>
</div>
<div id="map"></div>
</body>
</html>
你好我想问一下google地图API。以前,我是使用 Google 地图 API 的初学者。我想使用 select option
.
我试过在 youtube 上阅读文档和一些视频,在 Whosebug 上阅读其他帖子,但 none 其中符合我的要求。
我想制作如下图。当我按 select option
搜索时,将出现所选城市。当我点击标记时,我会看到地点描述,例如照片、地名和描述。
我可以制作这样的功能吗?我真的坚持我所做的,我已经制作了一些代码,如下所示。请帮助我,我真的需要你的帮助。
let map;
let places;
let infoWindow;
let markers = [];
let autocomplete;
const countryRestrict = {
country: "tangerang"
};
const MARKER_PATH = "https://developers.google.com/maps/documentation/javascript/images/marker_green";
const hostnameRegexp = new RegExp("^https?://.+?/");
const cities = {
jakarta: {
center: {
lat: -6.186286,
lng: 106.822746
},
zoom: 12
},
tangerang: {
center: {
lat: -6.336135,
lng: 106.676924
},
zoom: 11
}
};
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: cities["tangerang"].zoom,
center: cities["tangerang"].center,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false,
fullscreenControl: false,
});
infoWindow = new google.maps.InfoWindow({
content: document.getElementById("info-content")
});
autocomplete = new google.maps.places.Autocomplete(
document.getElementById("autocomplete"), {
types: ["(cities)"],
componentRestrictions: countryRestrict
}
);
places = new google.maps.places.PlacesService(map);
autocomplete.addListener("place_changed", onPlaceChanged);
document.getElementById("country").addEventListener("change", setAutocompleteCountry);
}
function setAutocompleteCountry() {
const country = document.getElementById("country").value;
if (country == "all") {
autocomplete.setComponentRestrictions({
country: []
});
map.setCenter({
lat: 15,
lng: 0
});
map.setZoom(2);
} else {
autocomplete.setComponentRestrictions({
country: country
});
map.setCenter(cities[country].center);
map.setZoom(cities[country].zoom);
}
}
#mapsContent {
position: relative;
}
#mapsContent #controls {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
position: absolute;
left: 50%;
top: 5%;
-webkit-transform: translate(-50%, -5%);
transform: translate(-50%, -5%);
background-color: #fff;
padding: 10px 30px;
border-radius: 10px;
z-index: 9;
}
#mapsContent #controls .city {
padding-right: 30px;
border-right: 1px solid #acacac;
margin-right: 20px;
}
#contactContent #mapsContent #controls h4 {
color: #16215C;
font-size: 13px;
margin: 0;
}
#contactContent #mapsContent #controls #country {
border: none;
cursor: pointer;
}
#map {
position: relative;
width: 100%;
height: 900px;
background-color: #CACACA;
border-radius: 10px;
z-index: 0;
}
<div class="container-fluid">
<div class="row" id="mapsContent">
<div id="controls">
<div class="city">
<h4>Kota</h4>
</div>
<select id="country">
<option value="all">All</option>
<option value="jakarta">DKI Jakarta</option>
<option value="tangerang" selected>Tangerang</option>
</select>
</div>
<div id="map"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places&v=weekly" async defer></script>
为了获得您想要的结果,您将不得不使用 Place Details and Place photo 请求。如前所述,选择城市后,您已知的公司地点将显示标记和信息窗口,显示该地点的详细信息和初始照片。
每个城市的地点都在一个 JSON 对象中,但是,它只有每个唯一的地点 ID。修改JSON对象时,可以利用google
的place id finder inputting your company address to get the place's unique place_id. It is alright to cache the place ID as indicated in the service specific terms为了进一步降低成本,您会看到我将 fields
参数指定为仅获取您需要的数据。您可以检查所有可用字段 here.
这是供您参考的 JSFiddle 示例:https://jsfiddle.net/pintsik999/0vjbep7h/
您还可以查看下面的代码:
"use strict";
let map;
let cities;
let markers = [];
var citiesObj = {
"cities": [{
"key": "DKI Jakarta",
"value": {
"city": "jakarta",
"center": {
"lat": -6.186286,
"lng": 106.822746
},
"zoom": 12,
//Since you know at least the address of the places, you can go here to get the unique place ID: https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder
"places": [{
"place_id": "ChIJB9Y8liH0aS4RemVuMOm5PFA"
},
{
"place_id": "ChIJA7dLFoL2aS4Rbu2LGxzIbAA"
}
]
}
}, {
"key": "Tangerang",
"value": {
"city": "tangerang",
"center": {
"lat": -6.336135,
"lng": 106.676924
},
"zoom": 11,
"places": [{
"place_id": "ChIJS3fhJPzkaS4RF8UTWV8LnLY"
}]
}
}]
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: -6.336135,
lng: 106.676924,
},
zoom: 10,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false,
fullscreenControl: false,
});
cities = document.getElementById("city");
cities.options.add(new Option('Select City', ''))
//value of cities are JSON objects to customize center and zoom of the map upon selection
for (var i = 0; i < citiesObj.cities.length; i++) {
cities.options.add(new Option(citiesObj.cities[i].key, JSON.stringify(citiesObj.cities[i].value)))
}
}
//add markers and infowindows on the places in the selected city
function cityChanged() {
//Hide/reset markers when city selection has changed.
deleteMarkers();
var selectedCity = JSON.parse(cities.value);
map.setCenter(new google.maps.LatLng(selectedCity.center));
//instantiate placedetail service
const service = new google.maps.places.PlacesService(map);
for (var i = 0; i < selectedCity.places.length; i++) {
const request = {
placeId: selectedCity.places[i].place_id,
//adding the fields parameter will allow you to specify the details that you only need so that you wont be billed unnecessarily for extra data that you don't use. Check all the available fields here: https://developers.google.com/maps/documentation/javascript/place-data-fields
fields: ["name", "formatted_address", "place_id", "geometry", "photos"],
};
service.getDetails(request, (place, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
addMarker(place);
}
});
}
}
function addMarker(place) {
var marker = new google.maps.Marker({
position: place.geometry.location,
map: map
});
addInfoWindow(marker, place);
markers.push(marker);
}
function addInfoWindow(marker, place) {
const infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(
"<img src='" + place.photos[0].getUrl() + " width='300' height='400'>" +
"<div><strong>" +
place.name +
"</strong><br>" +
"Place ID: " +
place.place_id +
"<br>" +
place.formatted_address +
"</div>"
);
infowindow.open(map, this);
});
}
function deleteMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
/* 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;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- REPLACE API KEY PLACEHOLDER -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div>
City:
<select id="city" onchange="cityChanged()">
</select>
</div>
<div id="map"></div>
</body>
</html>