我正在尝试使用多个视图在angular.dart
中创建单页应用,但我找不到加载 Google地图的实际示例视图被路由到。
我正在使用google_maps
包。在主div
页面中定义包含地图的index.html
元素时,它可以正常工作,但在视图中定义了map div时会引发异常:
'TypeError: Cannot read property 'offsetWidth' of null'
我认为这意味着在指令类加载时尚未呈现视图。如何在视图中加载Map?
这是路由器:
@InjectableService()
class DefaultRouteInitializer implements RouteInitializer {
init(Router router, ViewFactory view) {
router.root
..addRoute(
name: 'city',
path: '/city',
enter: view('view/city_view.html'));
}
}
和视图html:
<div city-ctrl>
<div class="row">
<div class="col-md-12">
<div id="city_map_canvas" style="width: 100px; height: 100px;"> </div>
</div>
</div>
</div>
指令类在创建实际地图时遇到问题:
import 'dart:html';
import 'package:angular/angular.dart';
import 'package:google_maps/google_maps.dart';
@NgDirective(
selector: '[city-ctrl]'
)
class CityController {
CityController() {
final mapOptions = new MapOptions()
..zoom = 8
..center = new LatLng(-34.397, 150.644)
..mapTypeId = MapTypeId.ROADMAP
;
final map = new GMap(querySelector("#city_map_canvas"), mapOptions);
}
}
答案 0 :(得分:1)
我设法通过让city-ctrl指令实现NgAttachAware接口方法attach()来实现这一点,并从那里启动Maps。构造函数显然是错误的。以下结果如下:
@NgDirective(
selector: '[city-ctrl]'
)
class CityController implements NgAttachAware {
CityController() {
}
attach() {
final mapOptions = new MapOptions()
..zoom = 8
..center = new LatLng(-34.397, 150.644)
..mapTypeId = MapTypeId.ROADMAP
;
final map = new GMap(querySelector("#city_map_canvas"), mapOptions);
}
}
答案 1 :(得分:1)
我尝试了GünterZöchbauer在我的@component中提出的解决方案。但它仍然不起作用(也许我犯了一些错误),之后我注意到我的gogole地图在shadwo dom.so我可以实现ShadowRootAware类和它在onShadowRoot方法上显示谷歌地图。因为onShadowRoot方法将被调用,直到html元素加载。 这是组件html:
<div id="addculture">
...some code
<div id="map-canvas"></div>
...some code
</div>
这是组件dart文件:
library culture_component;
import 'dart:async';
import 'package:angular/angular.dart';
import '../service/culture_story.dart';
import '../service/culture.dart';
import '../service/query_service.dart';
import 'dart:html';
import 'dart:js' show context, JsObject;
import 'package:google_maps/google_maps.dart';
@Component(selector: 'add-culture', templateUrl: '../lib/component/add_culture_component.html', cssUrl: '../lib/component/add_culture_component.css', publishAs: 'addCultureCmp')
class AddCultureComponent implements AttachAware, ShadowRootAware {
AddCultureComponent(RouteProvider routeProvider, this.queryService, this._http) {
//todo
}
@override
onShadowRoot(ShadowRoot shadowRoot) {
final mapOptions = new MapOptions()
..zoom = 8
..center = new LatLng(-34.397, 150.644)
..mapTypeId = MapTypeId.ROADMAP;
var mapDiv = shadowRoot.querySelector("#map-canvas");
final map = new GMap(mapDiv, mapOptions);
}
@override
attach() {
}
}