Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Google Map with polymer?

I'd like to display a Google Map inside a polymer element.

This map should be handled from outside of my component.

like image 289
Alexandre Ardhuin Avatar asked Nov 05 '13 15:11

Alexandre Ardhuin


1 Answers

Here's how to declare a simple custom element that contains a google map. In this example the map has to be handled manually outside of the component :

  • gmap.html
<polymer-element name="gmap-map">
  <template>
    <div id='mapView' style='height: 500px; width: 500px'></div>
  </template>
  <script type="application/dart" src="gmap.dart"></script>
</polymer-element>
  • gmap.dart
import 'package:google_maps/google_maps.dart';
import 'package:polymer/polymer.dart';

@CustomTag('gmap-map')
class MapElement extends PolymerElement {
  GMap map;

  MapElement.created() : super.created() {
    final mapOptions = new MapOptions()
      ..mapTypeId = MapTypeId.ROADMAP;
    final mapView = getShadowRoot('gmap-map').querySelector("#mapView");
    map = new GMap(mapView, mapOptions);
  }

  attached() {
    super.attached();

    // this allow to notify the map that the size of the canvas has changed.
    // in some cases, the map behaves like it has a 0*0 size.
    event.trigger(map, 'resize', []);
  }
}

Now you can use it in an html file like that (you access the map instance with the map getter on element) :

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>GMaps app</title>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <link rel="import" href="gmap.html">
    <script type="application/dart">
import 'dart:html';
import 'gmap.dart' as m;
import 'package:google_maps/google_maps.dart';
import 'package:polymer/polymer.dart';
main(){
  initPolymer();
  m.MapElement mapElement = querySelector('#myMap');
  mapElement.map
    ..panTo(new LatLng(48, 2.5))
    ..zoom = 5;
}
    </script>
    <script src="packages/browser/dart.js"></script>
    <script src="packages/browser/interop.js"></script>
  </head>
  <body>
    <h1>Gmaps</h1>
    <gmap-map id='myMap'></gmap-map>
  </body>
</html>
like image 53
Alexandre Ardhuin Avatar answered Oct 28 '22 07:10

Alexandre Ardhuin