Angular 2 谷歌地图实现 [英] Angular 2 google map implementation

查看:32
本文介绍了Angular 2 谷歌地图实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular 2 的新手.我想使用谷歌地图 API 提供方向服务并实现了 https://developers.google.com/maps/documentation/javascript/examples/directions-simple 到我的项目,如下面的代码所示.但由于某种原因,地图没有加载.有人可以帮我解决这个问题吗?

ma​​p.html

<头><meta name="viewport" content="initial-scale=1.0, user-scalable=no"><meta charset="utf-8"><title>路线服务</title><风格>html,正文{高度:500px;边距:0;填充:0;}#地图 {高度:500px;}#浮动面板{位置:绝对;顶部:10px;左:25%;z-索引:5;背景色:#fff;填充:5px;边框:1px 实心 #999;文本对齐:居中;font-family: 'Roboto','sans-serif';行高:30px;padding-left: 10px;}</风格><身体><div id="浮动面板"><b>开始:</b><select id="开始"><option value="chicago, il">芝加哥</option><option value="st louis, mo">圣路易斯</option><option value="joplin, mo">Joplin, MO</option><option value="oklahoma city, ok">俄克拉荷马城</option><option value="amarillo, tx">Amarillo</option><option value="gallup, nm">Gallup, NM</option><option value="flagstaff, az">Flagstaff, AZ</option><option value="winona, az">Winona</option><option value="kingman, az">金曼</option><option value="barstow, ca">Barstow</option><option value="san bernardino, ca">圣贝纳迪诺</option><option value="洛杉矶,加利福尼亚">洛杉矶</option></选择><b>结束:</b><select id="结束"><option value="chicago, il">芝加哥</option><option value="st louis, mo">圣路易斯</option><option value="joplin, mo">Joplin, MO</option><option value="oklahoma city, ok">俄克拉荷马城</option><option value="amarillo, tx">Amarillo</option><option value="gallup, nm">Gallup, NM</option><option value="flagstaff, az">Flagstaff, AZ</option><option value="winona, az">Winona</option><option value="kingman, az">金曼</option><option value="barstow, ca">Barstow</option><option value="san bernardino, ca">圣贝纳迪诺</option><option value="洛杉矶,加利福尼亚">洛杉矶</option></选择>

<div id="地图"></div><脚本>函数 initMap() {var DirectionsService = 新的 google.maps.DirectionsService;var DirectionDisplay = 新的 google.maps.DirectionsRenderer;var map = new google.maps.Map(document.getElementById('map'), {变焦:7,中心:{纬度:41.85,长度:-87.65}});方向显示.setMap(地图);var onChangeHandler = function() {计算AndDisplayRoute(方向服务,方向显示);};document.getElementById('start').addEventListener('change', onChangeHandler);document.getElementById('end').addEventListener('change', onChangeHandler);}函数计算AndDisplayRoute(方向服务,方向显示){路线Service.route({来源:document.getElementById('start').value,目的地:document.getElementById('end').value,旅行模式:'驾驶'},功能(响应,状态){如果(状态 === 'OK'){DirectionsDisplay.setDirections(响应);} 别的 {window.alert('由于'+状态,路线请求失败);}});}<脚本异步延迟src="https://maps.googleapis.com/maps/api/js?key=MY-KEY&callback=initMap"></html>

地图组件

import {Component} from '@angular/core';@成分({选择器:'地图',templateUrl: 'app/dashboard/features/map.html'})导出类 MapComponent {}

解决方案

找到了解决方案.

1) 在 index.html 中添加谷歌地图 api 脚本

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR-KEY]" 异步延迟></script>

2) 在您的 html 文件中只添加与 html 相关的代码.

ma​​p.html

3) 在单独的 css 文件或组件中添加样式相关代码.

ma​​p.css

 #map {高度:500px;}

4) 将 google 声明为变量.并在 ngOnInit() 方法中添加所有 javascript.

MapComponent.ts

声明 var google: any;@成分({选择器:'地图',templateUrl: 'app/dashboard/features/map.html',styleUrls: ['app/dashboard/features/map.css']})导出类 MapComponent 实现 OnInit、OnChanges {ngOnInit() {var DirectionsService = 新的 google.maps.DirectionsService;var DirectionDisplay = 新的 google.maps.DirectionsRenderer;var map = new google.maps.Map(document.getElementById('map'), {变焦:7,中心:{纬度:41.85,长度:-87.65}});方向显示.setMap(地图);计算AndDisplayRoute(方向服务,方向显示);函数计算AndDisplayRoute(方向服务,方向显示){var waypts = [];var checkboxArray:any[] = [温尼伯"、里贾纳"、卡尔加里"];for (var i = 0; i < checkboxArray.length; i++) {waypts.push({位置: checkboxArray[i],中途停留:真的});}路线Service.route({原点:{lat: 41.85, lng: -87.65},目的地:{lat: 49.3, lng: -123.12},航点:航点,优化航路点:真,旅行模式:'驾驶'},功能(响应,状态){如果(状态 === 'OK'){DirectionsDisplay.setDirections(响应);} 别的 {window.alert('由于'+状态,路线请求失败);}});}}

I'm new to angular 2. I wanted to use google map API for direction service and implemented the example shown in https://developers.google.com/maps/documentation/javascript/examples/directions-simple to my project as shown below code. But for some reason the map is not loading. Can someone help me with this?

map.html

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Directions service</title>
    <style>
      html, body {
        height: 500px;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 500px;
      }
      #floating-panel {
        position: absolute;
        top: 10px;
        left: 25%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }
    </style>
  </head>
  <body>        
    <div id="floating-panel">
    <b>Start: </b>
    <select id="start">
      <option value="chicago, il">Chicago</option>
      <option value="st louis, mo">St Louis</option>
      <option value="joplin, mo">Joplin, MO</option>
      <option value="oklahoma city, ok">Oklahoma City</option>
      <option value="amarillo, tx">Amarillo</option>
      <option value="gallup, nm">Gallup, NM</option>
      <option value="flagstaff, az">Flagstaff, AZ</option>
      <option value="winona, az">Winona</option>
      <option value="kingman, az">Kingman</option>
      <option value="barstow, ca">Barstow</option>
      <option value="san bernardino, ca">San Bernardino</option>
      <option value="los angeles, ca">Los Angeles</option>
    </select>
    <b>End: </b>
    <select id="end">
      <option value="chicago, il">Chicago</option>
      <option value="st louis, mo">St Louis</option>
      <option value="joplin, mo">Joplin, MO</option>
      <option value="oklahoma city, ok">Oklahoma City</option>
      <option value="amarillo, tx">Amarillo</option>
      <option value="gallup, nm">Gallup, NM</option>
      <option value="flagstaff, az">Flagstaff, AZ</option>
      <option value="winona, az">Winona</option>
      <option value="kingman, az">Kingman</option>
      <option value="barstow, ca">Barstow</option>
      <option value="san bernardino, ca">San Bernardino</option>
      <option value="los angeles, ca">Los Angeles</option>
    </select>
    </div>
    <div id="map"></div>
    <script>
      function initMap() {
        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: {lat: 41.85, lng: -87.65}
        });
        directionsDisplay.setMap(map);

        var onChangeHandler = function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        };
        document.getElementById('start').addEventListener('change', onChangeHandler);
        document.getElementById('end').addEventListener('change', onChangeHandler);
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        directionsService.route({
          origin: document.getElementById('start').value,
          destination: document.getElementById('end').value,
          travelMode: 'DRIVING'
        }, function(response, status) {
          if (status === 'OK') {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=MY-KEY&callback=initMap">
    </script>
  </body>
</html>

MapComponent

import {Component} from '@angular/core';

@Component({
    selector: 'map',
    templateUrl: 'app/dashboard/features/map.html'
}) 

export class MapComponent {}

解决方案

Found a solution for this.

1) Add google map api script in index.html

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR-KEY]" async defer></script>

2) Add only html related code in your html file.

map.html

<div id="map"></div>

3) Add style related codes in separate css file or in component.

map.css

      #map {
        height: 500px;
      }

4) Declare google as variable. And add all javascript in ngOnInit() method.

MapComponent.ts

declare var google: any;

@Component({
    selector: 'map',
    templateUrl: 'app/dashboard/features/map.html',
    styleUrls: ['app/dashboard/features/map.css']
}) 

export class MapComponent implements OnInit, OnChanges {

ngOnInit() {

        var directionsService = new google.maps.DirectionsService;
       var directionsDisplay = new google.maps.DirectionsRenderer;
       var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: {lat: 41.85, lng: -87.65}
        });
        directionsDisplay.setMap(map);
        calculateAndDisplayRoute(directionsService, directionsDisplay);

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {

          var waypts = [];
          var checkboxArray:any[] = [
              'winnipeg', 'regina','calgary'
      ];
      for (var i = 0; i < checkboxArray.length; i++) {

            waypts.push({
              location: checkboxArray[i],
              stopover: true
            });

        }

        directionsService.route({
          origin: {lat: 41.85, lng: -87.65},
          destination: {lat: 49.3, lng: -123.12},
          waypoints: waypts,
          optimizeWaypoints: true,
          travelMode: 'DRIVING'
        }, function(response, status) {
          if (status === 'OK') {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }

    }

这篇关于Angular 2 谷歌地图实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆