我有一个谷歌地图,上面已经有多个标记,最重要的是我有一个搜索字段,用户可以使用地址或纬度/经度搜索位置。当页面第一次加载时,我有一个可拖动的标记"com_current"落在某一点。之后,用户尝试从搜索字段进行搜索。应将此标记拖放到该位置。我正在使用地理完成。这显示了我搜索的位置,但我无法将此标记拖放到该位置。
var beaches = [
["Place A", 21.984606, 89.974250],
["West Bengal", 21.681855, 88.584980],
["Sea Beach", 21.617401, 87.500898]
];
var markers = [];
var map; //set scope here so various functions can use them
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(beaches[0][1], beaches[0][2]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var com_Image = {
url: 'assets/img/single.png',
size: new google.maps.Size(61, 72),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 32)
};
var infowindow = new google.maps.InfoWindow();
var marker, i;
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
for (i = 0; i < beaches.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(beaches[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
markers.push(marker);
}
//set marker to mainlocation
com_current = new google.maps.Marker({
map: map,
draggable: true,
icon: 'https://cdn.sstatic.net/Sites/askubuntu/img/favicon.ico?v=eff8fd315b9e',
animation: google.maps.Animation.DROP,
position: {
lat: 35.6895,
lng: 139.6917
}
});
$("#geocomplete").geocomplete({
details: "form"
}).bind("geocode:result", function(event, result) {
var myLatlng = new google.maps.LatLng(parseFloat(result.geometry.location.lat()), parseFloat(result.geometry.location.lng()));
console.log(result.geometry.location.lat());
map.panTo(myLatlng);
});
}
html,
body {
height: 100%;
margin: 20px auto;
padding: 0;
}
#map {
height: 100%;
}
#geocomplete {
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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initialize"
async defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/geocomplete/1.7.0/jquery.geocomplete.min.js"></script>
<input id="geocomplete" type="text" placeholder="Search Location">
<div id="map"></div>
您可以使用 marker.setPosition
方法:
marker.setPosition (new google.maps.LatLng( 48.864716, 2.349014 )); // Paris
在代码中,只需通过以下方法更改geocomplete
函数:
$("#geocomplete").geocomplete({
details: "form"
}).bind("geocode:result", function(event, result) {
var myLatlng = new google.maps.LatLng(parseFloat(result.geometry.location.lat()), parseFloat(result.geometry.location.lng()));
com_current.setPosition (myLatlng);
map.panTo(myLatlng);
});
如果您有任何问题或意见,请告诉我。