2012-11-19 29 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