我有一个带有默认标记的地图(连接用户的地址)和其他标记(数组中传递的地址),我有一个选择输入,地址在数组中传递,我喜欢当select选项更改视图时在所选选项的标记上更改地图, 是否可以在不更改默认标记的默认位置的情况下实现此功能?
答案 0 :(得分:1)
Yes, it is possible. Just create a new Google Maps Javascript API Marker using a new marker variable when your select input's 'change' event has been fired.
You can take a look at the sample code below:
var map;
function initMap() {
var defaultLoc = { "lat" : 37.7749295, "lng" :-122.4194155 };
map = new google.maps.Map(document.getElementById('map'), {
center: defaultLoc,
zoom: 8
});
var markerDefault = new google.maps.Marker({
position : defaultLoc,
map : map
});
document.getElementById('menuLoc').addEventListener('change', function(){
var that = this;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: that.value
}, function(result, status){
if ( status === 'OK' ) {
var newMarker = new google.maps.Marker({
position : result[0].geometry.location,
map: map
});
map.setCenter(result[0].geometry.location);
}
});
});
}
/* 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;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #FFF;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
<div id="floating-panel">
<select id="menuLoc">
<option value="fresno, ca, USA">Fresno</option>
<option value="sacramento, ca, usa">Sacramento</option>
<option value="carson city">Carson City</option>
</select>
</div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap"
async defer></script>
Hope it could and happy coding!