在打字稿类中创建谷歌地图实例



嗨,我是Typescript和Javascript的新手,我在创建googlemap实例时遇到了一些问题。

我已经下载了google.maps.d.ts声明文件并将其导入到我的打字稿类中,就像这样,所有的智能感知都工作正常等;

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":_。使用要求([])

为了加载谷歌地图api,我缺少什么?

提前谢谢。

当您在

页面上将 Google 地图作为script标签包含在内时,您可能不想使用模块加载器来加载它。

所以我会替换:

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

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

引用对 TypeScript 说"我将确保此脚本在运行时可用"。

导入语句说"在运行时为我加载此脚本"。

我喜欢创建一个名为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'); 

无论您想在哪里使用 Google 变量,只需将其包含在以下位置:

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

也许还可以看看打字 - 打字是管理和安装 TypeScript 定义的简单方法 - 这对我有很大帮助。

我目前正在编写另一个打字稿谷歌地图设置,并考虑与社区分享。

您可以使用此链接查看:https://github.com/DominikAngerer/typescript-google-maps

最新更新