2016-10-18 2 views
1

Я хотел бы создать карту компонент Google, которые работают так: https://jsfiddle.net/gvvy5vxz/2/Angular2 - Как настроить google.maps.OverlayView? (Перевести JS прототип в машинопись)

Он основан на следующем: https://developers.google.com/maps/documentation/javascript/examples/overlay-simple

Я новичок в машинопись и я застрял с реализацией прототипа, особенно с этим JS сниппет:

USGSOverlay.prototype = new google.maps.OverlayView(); 

USGSOverlay(bounds, image, map) { 

    // Initialize all properties. 
    this.bounds_ = bounds; 
    this.image_ = image; 
    this.map_ = map; 

    // Define a property to hold the image's div. We'll 
    // actually create this div upon receipt of the onAdd() 
    // method so we'll leave it null for now. 
    this.div_ = null; 

    // Explicitly call setMap on this overlay. 
    this.setMap(map); 
    } 

Я понятия не имею, как перевести это в машинописном образом и как объявлять вещи правильно.

Я думаю, я должен создать класс USGSOverlay, который расширяет google.maps.OverlayView, но он не работает.

class USGSOverlay extends google.maps.OverlayView{ 

    bounds_; 
    image_; 
    map_; 
    div_; 

    constructor(bounds, image, map){ 
    // Initialize all properties. 
    this.bounds_ = bounds; 
    this.image_ = image; 
    this.map_ = map; 

    // Define a property to hold the image's div. We'll 
    // actually create this div upon receipt of the onAdd() 
    // method so we'll leave it null for now. 
    this.div_ = null; 

    // Explicitly call setMap on this overlay. 
    this.setMap(map); 
    } 
} 

Этот компонент моей рабочей базы. Это создает простую карту внутри #Map:

import { Component } from '@angular/core'; 
declare const google: any; 
/* 
/* Component Map 
*/ 
@Component({ 
    selector: 'map', 
    template: ` 
    <div id="map"></div> 
    `, 
    styles: [ 
    `#map{ width:100%; height:100%; position: absolute; width:100%; height:100%; top:0; left:0;}` 
    ], 
}) 
export class MapComponent { 

    ngOnInit(){ 
    google.maps.event.addDomListener(window, 'load', this.initMap); 
    } 

    initMap() { 

    const map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 11, 
     center: {lat: 62.323907, lng: -150.109291}, 
     mapTypeId: google.maps.MapTypeId.SATELLITE 
    }); 

    const bounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(62.281819, -150.287132), 
     new google.maps.LatLng(62.400471, -150.005608)); 
    } 
} 

ответ

0

я был на хорошем пути он работает ...

import { Component } from '@angular/core'; 
declare const google: any; 

class USGSOverlay extends google.maps.OverlayView{ 

    bounds_; 
    image_; 
    map_; 
    div_; 

    constructor(bounds, image, map){ 
    // Initialize all properties. 
    this.bounds_ = bounds; 
    this.image_ = image; 
    this.map_ = map; 

    // Define a property to hold the image's div. We'll 
    // actually create this div upon receipt of the onAdd() 
    // method so we'll leave it null for now. 
    this.div_ = null; 

    // Explicitly call setMap on this overlay. 
    this.setMap(map); 
    } 

    /** 
    * onAdd is called when the map's panes are ready and the overlay has been 
    * added to the map. 
    */ 
    onAdd(){ 
    const div = document.createElement('div'); 
    div.style.borderStyle = 'none'; 
    div.style.borderWidth = '0px'; 
    div.style.position = 'absolute'; 

    // Create the img element and attach it to the div. 
    const img = document.createElement('img'); 
    img.src = this.image_; 
    img.style.width = '100%'; 
    img.style.height = '100%'; 
    img.style.position = 'absolute'; 
    div.appendChild(img); 

    this.div_ = div; 

    // Add the element to the "overlayLayer" pane. 
    const panes = this.getPanes(); 
    panes.overlayLayer.appendChild(div); 
    }; 

    draw(){ 

    // We use the south-west and north-east 
    // coordinates of the overlay to peg it to the correct position and size. 
    // To do this, we need to retrieve the projection from the overlay. 
    const overlayProjection = this.getProjection(); 

    // Retrieve the south-west and north-east coordinates of this overlay 
    // in LatLngs and convert them to pixel coordinates. 
    // We'll use these coordinates to resize the div. 
    const sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest()); 
    const ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast()); 

    // Resize the image's div to fit the indicated dimensions. 
    const div = this.div_; 
    div.style.left = sw.x + 'px'; 
    div.style.top = ne.y + 'px'; 
    div.style.width = (ne.x - sw.x) + 'px'; 
    div.style.height = (sw.y - ne.y) + 'px'; 
    }; 

    // The onRemove() method will be called automatically from the API if 
    // we ever set the overlay's map property to 'null'. 
    onRemove(){ 
    this.div_.parentNode.removeChild(this.div_); 
    this.div_ = null; 
    }; 
}; 



/* 
/* Component Map 
*/ 
@Component({ 
    selector: 'map', 
    template: ` 
    <div id="map"></div> 
    `, 
    styles: [ 
    `#map{ width:100%; height:100%; position: absolute; width:100%; height:100%; top:0; left:0;}` 
    ], 
}) 
export class MapComponent { 

    overlay; 

    ngOnInit(){ 
    google.maps.event.addDomListener(window, 'load', this.initMap); 
    } 

    initMap() { 

    const map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 11, 
     center: {lat: 62.323907, lng: -150.109291}, 
     mapTypeId: google.maps.MapTypeId.SATELLITE 
    }); 

    const bounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(62.281819, -150.287132), 
     new google.maps.LatLng(62.400471, -150.005608)); 

    // The photograph is courtesy of the U.S. Geological Survey. 
    const srcImage = 'https://developers.google.com/maps/documentation/' + 
     'javascript/examples/full/images/talkeetna.png'; 

    // The custom USGSOverlay object contains the USGS image, 
    // the bounds of the image, and a reference to the map. 
    this.overlay = new USGSOverlay(bounds, srcImage, map); 
    } 
} 
0

Я также имел кучу неприятностей с этим, но в конце концов пришел прямо. Очень важно, чтобы скрипт Google Maps был предварительно загружен (я загрузил мой в свой маршрут resolver), иначе вы получите «google» не определенную ошибку. См. here о том, как я установил типизацию и импортировал библиотеку.

Что касается синтаксиса, для этого я использовал для этого внутренний класс. Это происходит потому, что, если это класс верхнего уровня WebPack попытки (безуспешно), чтобы найти библиотеку Google Maps во время компиляции:

// import typings 
import {} from '@types/googlemaps'; 

@Component({...}) 
export class MapComponent implements OnInit { 
    // weird syntax, I know, but it works 
    USGSOverlay = class extends google.maps.OverlayView { 
    constructor(bounds, image, private map){ 
     super(); 
     ... 
     this.setMap(this.map); 
    } 
    onAdd(){...} 
    draw(){...} 
    } 
    ngOnInit() { 
    const overlay = new this.Overlay(bounds, image, map); 
    } 
} 
1

Вот что работает для меня (с помощью ионной 2):

  1. Используйте следующие команды:

    npm install typings --global 
    typings install dt~google.maps --global --save 
    typings install google.maps --global 
    
  2. Добавить "типизации/* d.ts" в вашем tsconfig.json:

    "include": [ 
        "src/**/*.ts", 
        "typings/*.d.ts" 
    ] 
    
  3. Вот код Машинопись:

    import { Component, ViewChild, ElementRef } from '@angular/core'; 
    import { NavController } from 'ionic-angular'; 
    // import typings 
    import { } from '@types/googlemaps'; 
    /* 
    /* Component Map 
    */ 
    @Component({ 
        selector: 'page-overlay', 
        templateUrl: 'overlay.html' 
    }) 
    export class OverlayPage { 
        @ViewChild('map') mapElement: ElementRef; 
        map: any; 
        // weird syntax, I know, but it works 
        constructor(public navCtrl: NavController) { 
        } 
        USGSOverlay = class extends google.maps.OverlayView { 
         bounds_: any; 
         image_: any; 
         map_: any; 
         div_: any; 
         constructor(bounds, image, private map) { 
          super(); 
          // Initialize all properties. 
          this.bounds_ = bounds; 
          this.image_ = image; 
          this.map_ = map; 
          // Define a property to hold the image's div. We'll 
          // actually create this div upon receipt of the onAdd() 
          // method so we'll leave it null for now. 
          this.div_ = null; 
          // Explicitly call setMap on this overlay. 
          this.setMap(map); 
          this.set 
         } 
         /** 
         * onAdd is called when the map's panes are ready and the overlay has been 
         * added to the map. 
         */ 
         onAdd() { 
          const div = document.createElement('div'); 
          div.style.borderStyle = 'none'; 
          div.style.borderWidth = '0px'; 
          div.style.position = 'absolute'; 
          // Create the img element and attach it to the div. 
          const img = document.createElement('img'); 
          img.src = this.image_; 
          img.style.width = '100%'; 
          img.style.height = '100%'; 
          img.style.position = 'absolute'; 
          div.appendChild(img); 
          this.div_ = div; 
          // Add the element to the "overlayLayer" pane. 
          const panes = this.getPanes(); 
          panes.overlayLayer.appendChild(div); 
         }; 
         draw() { 
          // We use the south-west and north-east 
          // coordinates of the overlay to peg it to the correct position and size. 
          // To do this, we need to retrieve the projection from the overlay. 
          const overlayProjection = this.getProjection(); 
          // Retrieve the south-west and north-east coordinates of this overlay 
          // in LatLngs and convert them to pixel coordinates. 
          // We'll use these coordinates to resize the div. 
          const sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest()); 
          const ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast()); 
          // Resize the image's div to fit the indicated dimensions. 
          const div = this.div_; 
          div.style.left = sw.x + 'px'; 
          div.style.top = ne.y + 'px'; 
          div.style.width = (ne.x - sw.x) + 'px'; 
          div.style.height = (sw.y - ne.y) + 'px'; 
         }; 
         // The onRemove() method will be called automatically from the API if 
         // we ever set the overlay's map property to 'null'. 
         onRemove() { 
          this.div_.parentNode.removeChild(this.div_); 
          this.div_ = null; 
         }; 
        }; 
        ngOnInit() { 
         this.loadMap(); 
         var bounds = new google.maps.LatLngBounds(
          new google.maps.LatLng(62.281819, -150.287132), 
          new google.maps.LatLng(62.400471, -150.005608)); 
         // The photograph is courtesy of the U.S. Geological Survey. 
         var srcImage = 'https://developers.google.com/maps/documentation/' + 
          'javascript/examples/full/images/talkeetna.png'; 
         const overlay = new this.USGSOverlay(bounds, srcImage, this.map); 
         //overlay.setMap(this.map); 
        } 
        ionViewDidLoad() { 
         this.loadMap(); 
         var bounds = new google.maps.LatLngBounds(
          new google.maps.LatLng(62.281819, -150.287132), 
          new google.maps.LatLng(62.400471, -150.005608)); 
         // The photograph is courtesy of the U.S. Geological Survey. 
         var srcImage = 'https://developers.google.com/maps/documentation/' + 
          'javascript/examples/full/images/talkeetna.png'; 
         const overlay = new this.USGSOverlay(bounds, srcImage, this.map); 
         //overlay.setMap(this.map); 
        } 
        loadMap() {   
         let latLng = new google.maps.LatLng(62.323907, -150.109291); 
         var mapOptions = { 
          zoom :15, 
          center : latLng, 
          enableHighAccuracy: true, 
          timeout: 5000, 
          maximumAge: 0 
         }; 
         this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions); 
        } 
    } 
    
Смежные вопросы