如何通过按钮点击更改谷歌地图类型?

时间:2016-06-08 18:01:44

标签: javascript html angularjs google-maps-api-3 angularjs-directive

我为谷歌地图做了一个指令,允许传递mapType和地址值:

.directive('map', function(){
return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    scope: {
        'address': "@",
        'mapType': "@"
    },
    link: function(scope, element, attrs) {
        console.log(scope, attrs);
        var geoCoder = new google.maps.Geocoder();
        geoCoder.geocode(
            {'address': scope.address},
            function(result, status){
                console.log(result, status);
                if(status==="OK"){
                    map.setCenter(result[0].geometry.location);
                    marker.setPosition(result[0].geometry.location);
                }
            }
        );
        var mapOptions = {
            zoom: 16,
            mapTypeId: eval(scope.mapType),
            draggable: false
        };
        if(scope.mapType === undefined || scope.mapType === ""){
           mapOptions.mapTypeId = google.maps.MapTypeId.ROADMAP; 
        }
        var map = new google.maps.Map(document.getElementById(attrs.id), mapOptions);
        var marker = new google.maps.Marker({
            map: map,
        })
    }
  };
})

我还制作了一个控制器来控制我要传递的地图类型:

$scope.mapModules = [
    {
        text: "街道地图",
        value: "google.maps.MapTypeId.ROADMAP"
    },
    {
        text: "鸟瞰地图",
        value: "google.maps.MapTypeId.SATELLITE"
    }
];

$scope.selected = $scope.mapModules[0];
$scope.mapType = $scope.mapModules[0].value;

$scope.select = function(item){
    console.log(item);
    $scope.selected = item;
    $scope.mapType = item.value;
};

这是查看地图的视图层:

<div class="row noPadding">
    <div ng-click="select(option)" class="col textCenter mapOption" ng-class="{'mapOptionActived': option == selected}" ng-repeat="option in mapModules">
          {{option.text}}
    </div>
</div>
<map map-type="{{mapType}}" id="schoolMap" style="height: 200px; width:100%" address="2140 w 41st Vancouver, BC"></map>

首先加载页面时一切正常,但是当我点击地图模块按钮时,地图类型不会改变。所以我正在寻找允许用户在点击选项按钮时更改地图类型的解决方案。

谢谢。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

var mapType = "ROADMAP";
map.setMapTypeId(google.maps.MapTypeId[mapType]);