我正在使用google maps api并且需要在搜索框中显示标记,此标记将使用我在数据库中的lat和long,但如果拖动或有人使用搜索框则会更改。我设法加载地图并将其居中在坐标上,但它没有显示标记,在我使用搜索框后所有工作。 我尝试在代码的开头添加一个标记,但没有成功,它在我使用函数时创建了一个新标记:
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var latitude = ;
var longitude = ;
var zoom = "+MapZoom+";
var LatLng = new google.maps.LatLng(51.501476, -0.140634);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: '"+Latitude+"',
draggable: true
});
这是我目前的代码,我确定我只是遗漏了一些任何帮助将不胜感激
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(51.501476, -0.140634));
map.fitBounds(defaultBounds);
var input = (document.getElementById('pacinput')
);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var marker = new google.maps.Marker({
draggable: true,
map: map,
title: place.name,
position: place.geometry.location
});
// drag response
google.maps.event.addListener(marker, 'dragend', function(e) {
displayPosition(this.getPosition());
});
// click response
google.maps.event.addListener(marker, 'click', function(e) {
displayPosition(this.getPosition());
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
// displays a position on two <input> elements
function displayPosition(pos) {
document.getElementById('Latitude').value = pos.lat();
document.getElementById('Longitude').value = pos.lng();
}
}
google.maps.event.addDomListener(window, 'load', initialize);
initialize();
</script>"
答案 0 :(得分:0)
根据我的理解,您希望标记在页面加载到地图居中的同一位置时尝试使用
var map;
var marker;
$(document).ready(function(){
initialize();
drawmarker();
darggable();
});
function initialize() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
function drawmarker(){
marker = new google.maps.Marker({
position : new google.maps.LatLng(51.508742,-0.120850),
title:"this s it",
map : map,
draggable:true,
})
}
将您的标记设为全局,现在使用dragend上的方法
function darggable(){
google.maps.event.addListener(marker, 'dragend', function(e) {
console.log(e.latLng.lat(),e.latLng.lng())
});
}
现在你得到latlng现在用它来显示在文本框中