2012-11-19 32 views
10

嗨我是新來的Typescript和Javascript,並且我在創建googlemap實例時遇到了一些問題。在打字稿類中創建Google Map實例

我已經下載了google.maps.d.ts聲明文件,並將它導入到我的打字稿類中,所有intellisense都能正常工作。

import googleMaps = module("google.maps"); 
module Mapping { 
    export class GoogleMap implements IMap { 

     public name: string; 
     private map: any; 
     private options: any; 

     constructor (mapDiv:Element) { 
      this.name = "GoogleMap"; 
      this.options = { zoom: 3, MapTypeId: 'terrian' }; 
      this.map = new googleMaps.google.maps.Map(mapDiv, this.options); 
     } 
    } 
} 

當我嘗試在我的index.cshtml文件中創建此類時;

<!DOCTYPE html> 
<html> 
    <head><title>TypeScript Mapping</title></head> 
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js? key=MYKEYGOESHERE&sensor=false"></script> 
    <script type="text/javascript" src="~/scripts/require.js"></script> 
    <script type="text/javascript" src="~/typings/Mapping.js"></script> 
    <script type="text/javascript"> 
     function initialize() { 

      var mapCanvas = document.getElementById("map"); 

      var googleMap = new Mapping.GoogleMap(mapCanvas); 
     } 
    </script> 
<body onload="initialize()"> 
<div id="map" style="height: 512px; width: 512px;"></div> 

我碰到下面的錯誤;

Microsoft JScript運行時錯誤:模塊名稱「google.maps」尚未加載上下文:_。使用require([])

我爲了加載googlemaps api而丟失了什麼?

在此先感謝。

回答

13

當你在包括谷歌地圖爲您的網頁上script標籤,你可能不希望使用一個模塊加載器加載它

所以我將取代:

import googleMaps = module("google.maps"); 

With

/// <reference path="./google.maps.d.ts" /> 

對TypeScript的引用「我將確保此腳本在運行時可用」。

import語句顯示「在運行時爲我加載這個腳本」。

+0

感謝史蒂夫,我給一個去當我回到辦公室 –

+0

那偉大工程,感謝您的信息和解釋。 –

0

我喜歡創建一個名爲shim的函數,它可以讓我使用窗口變量/對象(如google)。我創建了.ts文件:

// -- Shim.ts: 

/** 
* Loads variable from window according to 
* the name parameter. 
* 
* @export 
* @param {string} name 
* @returns {*} window[name] 
*/ 
export function shim(name: string): any { 
    let global: any = window; 
    return global[name]; 
} 

我的基本設置比看起來像:

- main.ts 
-- shims 
-- -- Shim.ts 
-- -- Google.ts 
-- -- Swiper.ts 
-- -- ... .ts 

和Google.ts會比單純使用該功能,如:

// -- Google.ts 

import { shim } from '../shims/Shim'; 

/** 
* Loads variable from window with the 
* name 'google' 
* 
* @export 
* @returns {*} window['google'] 
*/ 
export let google = shim('google'); 

和等。無論您比想要使用谷歌變量簡單地包括它像:

import { google } from '../shims/Google'; 

也許你也看看typings - Typings是管理和安裝TypeScript定義的簡單方法 - 這對我有很大的幫助。

我目前編寫了另一個Typescript Google Maps安裝程序,並考慮與社區共享它。

你可以檢查出來使用此鏈接:https://github.com/DominikAngerer/typescript-google-maps