2017.6.7
2020.6.5

Googleマップのプレイス情報を取得して表示する(angular-google-maps)

AngularJSのGoogleマップ用ライブラリ「angular-google-maps」を使って、マップ上に配置したマーカーをクリックした際に、プレイス情報を取得して、取得したデータを画面に表示する方法です。ライブラリを使うために必要なものについては、「WebサイトにGoogleマップを埋め込む」の記事を確認して下さい。

以下の記事で使用しているメソッド「radarSearch()」は、現在(2018年7月30日まで)は使えなくなっています。呼び出すメソッドを最新のものに置き換えるなどして対応してください。

目次

  • コード
  • 動作確認
  • 参考リンク

コード

関係ないコードについては極力削除しているので、適宜、補完して下さい。

◆html


<ui-gmap-google-map center="map.center" zoom="map.zoom" options="map.options" ng-if="map">
    <ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
    </ui-gmap-marker>
</ui-gmap-google-map>

◆javascript


var myApp = angular.module('myApp', ['uiGmapgoogle-maps']);

myApp.config(function (uiGmapGoogleMapApiProvider) {
    uiGmapGoogleMapApiProvider.configure({
        v: '3.28',
        language:'ja',
        libraries: 'weather,geometry,visualization,places',
        key: 'YOUR_API_KEY'
    });
});

myApp.controller('exampleCtrl', function ($scope, uiGmapGoogleMapApi, uiGmapIsReady) {
    uiGmapGoogleMapApi.then(function(maps) {
        var data = [
            { lat: 35.681167, lng: 139.767052, title: "東京駅" },
            { lat: 35.693318, lng: 139.749885, title: "日本武道館" },
            { lat: 35.685175, lng: 139.7528, title: "皇居" }
        ];
        
        $scope.map = { 
            center: { latitude: data[0].lat, longitude: data[0].lng }, 
            zoom: 13,
            options: {
              mapTypeId: google.maps.MapTypeId.ROADMAP
            } 
        };
        
        $scope.markers = [];
        for (var i = 0; i < data.length; i++){
            $scope.markers.push({
                id: i,
                coords: { latitude: data[i].lat, longitude: data[i].lng },
                options: { title: data[i].title }
            });
        }
        
        // プレイス情報の取得・表示
        var placesService;
        uiGmapIsReady.promise().then(function(instances) {
            placesService = new maps.places.PlacesService(instances[0].map);
	    });
        
        $scope.showPlaceInfo = function(marker, eventName, args){
            placesService.radarSearch({ 
                location: {
                    lat: marker.getPosition().lat(), 
                    lng: marker.getPosition().lng()
                }, 
                radius: '500', 
                name: marker.getTitle()
            }, function(results, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    getPlaceDetails(results[0].place_id);
                }
            });
        };
        
        function getPlaceDetails(placeId){
            placesService.getDetails({ placeId: placeId }, function(result, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    showPlaceInfo(result);
                }
            });
        }
        
        function showPlaceInfo(place){
            var placeData = {};
            placeData.place_id = place.place_id;
            placeData.name = place.name;
            placeData.formatted_address = place.formatted_address;
            placeData.formatted_phone_number = place.formatted_phone_number;
            placeData.rating = place.rating;
            placeData.url = place.url;          // グーグルマップ用のURL
            placeData.website = place.website;  // 会社のホームページなど、このプレイスの公式ウェブサイト
            
            placeData.reviews = [];
            place.reviews.forEach(function(item, i){
                placeData.reviews.push({
                    author_name: item.author_name,
                    author_url: item.author_url,
                    rating: item.rating,
                    relative_time_description: item.relative_time_description,
                    text: item.text
                });
            });
            
            placeData.photos = [];
            place.photos.forEach(function(item, i){
                placeData.photos.push({
                    url: item.getUrl({maxWidth: 640})
                });
            });
            
            $scope.place = placeData;
        }
    });
});

configの「libraries」設定で「places」を指定します。

プレイス情報の取得に「google.maps.places.PlacesService()」を利用しているので、「angular-google-maps」を利用しているのはマーカーを表示している個所のみになります。

処理の流れは、radarSearch()で「place_id」を特定して、その「place_id」を元にgetDetails()で詳細なプレイス情報を取得しています。

画像(photo)のURLを取得する場合、上記ではgetUrl({maxWidth: 640})としていますが、「maxWidth」は必須の項目になります。未指定の場合は以下のようなエラーが出ます。

Uncaught TypeError: Cannot read property 'maxWidth' of undefined

また「Google Places API Web Service」を有効にしないと以下のエラーが出ます。

This API project is not authorized to use this API. Please ensure this API is activated in the Google Developers Console: https://console.developers.google.com/apis/api/places_backend?project=_ For more information on authentication and Google Maps Javascript API services please see: https://developers.google.com/maps/documentation/javascript/get-api-key

動作確認

マップ上のマーカーをクリックすると、下記にプレイス検索で取得した情報(一部)を表示します。

place_id{{place.place_id}}
name{{place.name}}
formatted_address{{place.formatted_address}}
formatted_phone_number{{place.formatted_phone_number}}
rating{{place.rating}}
url{{place.url}}
website{{place.website}}
reviews[{{$index}}]
author_name{{review.author_name}}
author_url{{review.author_url}}
rating{{review.rating}}
relative_time_description{{review.relative_time_description}}
text{{review.text}}
photos[{{$index}}]

参考リンク

AngularJS】関連記事