我在Ionic2中有一个谷歌地图实现。地图和地理位置工作正常。只有在我尝试在地图中实现自定义控件/按钮后才会出现错误。我按照这个链接: https://developers.google.com/maps/documentation/javascript/examples/control-custom
这是我的js代码(构造函数):
constructor(navController, platform, app) {
this.navController = navController;
this.platform = platform;
this.app = app;
platform.ready().then(() => {
this.initializeMap();
});
}
自定义控制:
CenterControl(controlDiv, map){
// Set CSS for the control border.
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = '#fff';
controlUI.style.border = '2px solid #fff';
controlUI.style.borderRadius = '3px';
controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
controlUI.style.cursor = 'pointer';
controlUI.style.marginBottom = '22px';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to recenter the map';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior.
var controlText = document.createElement('div');
controlText.style.color = 'rgb(25,25,25)';
controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.lineHeight = '38px';
controlText.style.paddingLeft = '5px';
controlText.style.paddingRight = '5px';
controlText.innerHTML = 'Center Map';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map to Chicago.
controlUI.addEventListener('click', function() {
map.setCenter(chicago);
});
}
地图初始化:
initializeMap() {
let locationOptions = {timeout: 10000, enableHighAccuracy: true};
navigator.geolocation.getCurrentPosition(
(position) => {
let options = {
// /new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById("map_canvas"), options);
var centerControlDiv = document.createElement('div');
var centerControl = new CenterControl(centerControlDiv, options);
centerControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
},
(error) => {
console.log(error);
}, locationOptions
);
}
我的index.html:
<script src="http://maps.google.com/maps/api/js?key=<MY API KEY>"></script>
第87行指的是:
var centerControl = new CenterControl(centerControlDiv, options);
我无法设置&#34; CenterControl(){}&#34; as&#34; function CenterControl(){}&#34;因为在那种情况下我会遇到语法错误。
答案 0 :(得分:1)
我会像这样定义CenterControl
:
export class CenterControl {
constructor(controlDiv, map){
(...)
}
}
而不是
CenterControl(controlDiv, map) {
(...)
}
并在您想要使用时导入...不要忘记export
关键字。
修改强>
如果这是你班级的一种方法,只需按照这种方式调用:
this.CenterControl(centerControlDiv, options);
centerControlDiv.index = 1;
this.map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);