Angular Google Maps で最低限のページを作る
とても苦労したので自分用にメモです。
使用環境
OS: Windows10 Education 64bit
IDE: Microsoft Visual Studio 2015 Community
Node.js: v6.9.1
AngularJS: v1.5.8
angular-google-maps: v2.4.0
下準備
Angular Google Mapsのインストール
コマンドプロンプトから、ページを作るフォルダで以下のようにインストールします。
bower install angular-google-maps
Google MapのAPIキーを取得
2016年6月22日より、APIキーの取得が必要になったようです。キーがないと正しく表示されない場合があります。GoogleマップのAPIキーのエラーが出る時の対処法を参考にしました。(閲覧日: 2016/11/26)
Google Maps APIsのページに行き、"GET A KEY"ボタンを押して、必要に応じてプロジェクトを作成・選択しAPIを有効にします。取得したキーの文字列は後で使用しますので、メモしておきます。
コーディング
HTML
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8" />
<title>AngularJS</title>
<link rel="stylesheet" href="css/map.css" />
<!-- Google Map API キーが必要-->
<script src='//maps.googleapis.com/maps/api/js?sensor=false&取得したキー'></script>
<script src="bower_components/lodash/dist/lodash.min.js"></script>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-simple-logger/dist/angular-simple-logger.min.js"></script>
<script src="bower_components/angular-google-maps/dist/angular-google-maps.min.js"></script>
<script src="scripts/map.js"></script>
</head>
<body ng-controller="MyController">
<ui-gmap-google-map center="map.center" zoom="map.zoom" options="map.options">
</ui-gmap-google-map>
</body>
</html>
上記コードの、
<script src='//maps.googleapis.com/maps/api/js?sensor=false&"取得したキー"'></script>
の部分に、先ほど取得したGoogle Maps APIのキーを入力します。これがないと正しく表示されません。
JavaScript
map.js
var myApp = angular.module('myApp', ['uiGmapgoogle-maps'])
myApp.controller('MyController', ['$scope', 'uiGmapGoogleMapApi', map]);
function map($scope, uiGmapGoogleMapApi) {
var latlng = new google.maps.LatLng(35.893868, 139.952540);//柏の葉キャンパス駅
$scope.map = {
zoom: 14,// 縮尺の度合い
center: latlng,// 中心座標
disableDefaultUI: true, // デフォルトのUIの有効/無効
mapTypeId: google.maps.MapTypeId.ROADMAP // マップのタイプ
};
}
CSS
map.css
.angular-google-map-container {
height: 400px;
width: 600px;
}
表示するマップの高さ・幅を指定してあげないといけないようです。