我只希望标记应居中,地图应可拖动
getCurrentLocation() {
this.geolocation.getCurrentPosition().then((position) => {
let geo = new google.maps.Geocoder;
this.location.lat = position.coords.latitude;
this.location.lng = position.coords.longitude;
var latlng = { lat: this.location.lat, lng: this.location.lng };
geo.geocode({ 'location': latlng }, (results) => {
if (results.length) {
let address = results[0];
this.position = {
lat: address.geometry.location.lat,
lng: address.geometry.location.lng,
name: address.address_components[1].long_name,
dsc: address.formatted_address,
};
console.log(this.position, 'address current')
}
});
});
this.mapOptions = {
center: this.location,
zoom: 16,
mapTypeControl: false,
draggable: true, //map is draggable but marker doesnt stay in centre
};
setTimeout(() => {
this.map = new google.maps.Map(this.mapElement.nativeElement, this.mapOptions);
this.markerOptions.position = this.location;
this.markerOptions.map = this.map;
this.markerOptions.title = 'My Location';
this.marker = new google.maps.Marker(this.markerOptions);
}, 3000);
}
当用户打开地图时,当他能够移动地图时,地图应可拖动并且标记应居中
答案 0 :(得分:0)
这是解决您的问题map-how-to-keep-marker-in-center
的代码<div id="map_canvas">
<img src="assets/marker.png" id="centerMarkerImg">
</div>
css
#map_canvas {
position: relative;
}
#centerMarkerImage {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom:0;
margin: auto;
width: 32px; // image width
height: 24px; // image height
z-index: 1;
}
.ts
export class HomePage {
dummyMarker: any;
mapDragMode: boolean = false;
centerPos: any;
ionViewDidLoad() {
this.dummyMarker = document.getElementById("centerMarkerImg");
this.dummyMarker.style.display = 'none';
}
loadMap() {
this.map.on(GoogleMapsEvent.CAMERA_CHANGE).subscribe((params: any[]) => {
if (!this.mapDragMode) {
return;
}
const cameraPosition: any = params[0];
this.centerPos = cameraPosition.target;
});
}
start() : {
this.mapDragMode = true;
this.dummyMarker.style.display = 'block';
}
end() : {
this.mapDragMode = false;
this.dummyMarker.style.display = 'none';
}
}
答案 1 :(得分:0)
希望!!这可以帮助任何人...
addMarker() {
setTimeout(() => {
this.map = new google.maps.Map(this.mapElement.nativeElement, this.mapOptions);
this.markerOptions.position = this.map.getCenter();
this.markerOptions.map = this.map;
this.markerOptions.draggable = false;
this.markerOptions.title = 'My Location';
this.marker = new google.maps.Marker(this.markerOptions);
this.marker.bindTo('position', this.map, 'center'); //bind marker to be in center
google.maps.event.addListener(this.marker, 'dragend', () => {
this.map.setCenter(this.marker.getPosition()); // Set map center to marker position
});
google.maps.event.addListener(this.map, 'dragend', () => {
this.marker.setPosition(this.map.getCenter()); // set marker position to map center
});
}, 100);
}
或者其他方式:
访问此链接:demo