Monday, June 20, 2016

Google map api v3 with Ionic framework

My web was using Ionic framwork 1.x. After I read some threads and examples on the web, initiate the google map as following is the only way I can make the map show up.

index.html
<script src="http://maps.googleapis.com/maps/api/js?key=yourAPIkey&libraries=places" async defer></script>              

view html:
 <ion-header-bar class="bar bar-header bar-positive" ng-init="initMap()"></ion-header-bar>

<ion-content>          
       <div id="map" data-tap-disabled="true"></div>          
</ion-content>

javascript:
$scope.initMap = function() {
        $scope.directionsService = new google.maps.DirectionsService;
        $scope.directionsDisplay = new google.maps.DirectionsRenderer({
            suppressMarkers:true,
            preserveViewport: true
            //polylineOptions: { strokeColor: "red" }
        });
        var mylocation = new google.maps.LatLng('41.72', '-71.93');
        var grayStyles = [
            {   featureType: "all",
                elementType: "labels.text",
                stylers: [
                  { gamma: 0.01 }
                ]
            },
        ];
        var mapOptions = {
            center: mylocation,
            zoom: 11,
            styles: grayStyles,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"),
            mapOptions);      
        $scope.directionsDisplay.setMap(map);  
        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(map);

        marker = new google.maps.Marker({
            position: mylocation ,
            icon: "http://maps.google.com/mapfiles/kml/pal3/icon48.png",
            map: map
        });
        marker.infowindow = new google.maps.InfoWindow({                  
            content: 'My xxx Inc.'
        });              
        google.maps.event.addListener(marker, 'click', (function(marker) {
            return function() {                          
                    marker.infowindow.open(map, marker);
            }
        })(marker));  
     
        $scope.map = map;            
             
    };

No comments: