2016-02-03 76 views
-2

我以下面的地圖爲基礎。這是一個非常規則的地圖。根據情況更改Maps API樣式

function initMap() { 
    var map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 2, 
     center: {lat: 23.9096187, lng: -29.6761281}, 
     mapTypeId: google.maps.MapTypeId.SATELLITE, 
     disableDefaultUI: true 
    }); 
    } 

但是!如果某個條件成立,我想實現這些樣式(例如,如果var temp> 80,請添加此樣式)。這可能嗎?

{ 
    stylers: [ 
     {hue: '#890000'}, 
     {visibility: 'simplified'}, 
     {gamma: 0.5}, 
     {weight: 0.5} 
    ] 
    }, 
    { 
    elementType: 'labels', 
    stylers: [{visibility: 'off'}] 
    }, 
    { 
    featureType: 'water', 
    stylers: [{color: '#890000'}] 
    } 
], { 
    name: 'Custom Style' 
    }); 
var customMapTypeId = 'custom_style'; 

    map.mapTypes.set(customMapTypeId, customMapType); 
    map.setMapTypeId(customMapTypeId); 
+0

。當然您可以動態地改變風格。你做了什麼沒有奏效? – geocodezip

回答

1

您可以在地圖風格隨時致電更改爲您定義的樣式:

map.setOptions({ 
    styles: [{ 
    stylers: [{ 
     hue: '#890000' 
    }, { 
     visibility: 'simplified' 
    }, { 
     gamma: 0.5 
    }, { 
     weight: 0.5 
    }] 
    }, { 
    elementType: 'labels', 
    stylers: [{ 
     visibility: 'off' 
    }] 
    }, { 
    featureType: 'water', 
    stylers: [{ 
     color: '#890000' 
    }] 
    }] 
}); 

假設條件是,map在範圍(或使其全球性的,或者創建更改它的功能自從map以來,你的initMap函數的作用域對該函數來說就是lolocal)。

proof of concept fiddle

代碼片段:

function initialize() { 
 
    var map = new google.maps.Map(
 
    document.getElementById("map_canvas"), { 
 
     center: new google.maps.LatLng(37.4419, -122.1419), 
 
     zoom: 13, 
 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
 
    }); 
 
    var toggle = true; 
 
    google.maps.event.addDomListener(document.getElementById("btn"), 'click', function() { 
 
    if (toggle) { 
 
     map.setOptions({ 
 
     styles: [{ 
 
      stylers: [{ 
 
      hue: '#890000' 
 
      }, { 
 
      visibility: 'simplified' 
 
      }, { 
 
      gamma: 0.5 
 
      }, { 
 
      weight: 0.5 
 
      }] 
 
     }, { 
 
      elementType: 'labels', 
 
      stylers: [{ 
 
      visibility: 'off' 
 
      }] 
 
     }, { 
 
      featureType: 'water', 
 
      stylers: [{ 
 
      color: '#890000' 
 
      }] 
 
     }] 
 
     }); 
 

 
    } else { 
 
     map.setOptions({ 
 
     styles: [] 
 
     }); 
 
    } 
 
    toggle = !toggle; 
 
    }); 
 
} 
 
google.maps.event.addDomListener(window, "load", initialize);
html, 
 
body, 
 
#map_canvas { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0px; 
 
    padding: 0px 
 
}
<script src="https://maps.googleapis.com/maps/api/js"></script> 
 
<input id="btn" type="button" value="change style" /> 
 
<div id="map_canvas"></div>

+0

感謝您的幫助!是的,我意識到一些事情: 1 - 映射的所有樣式和動態編輯需要在原始initMap()函數內。 2 - 需要設置不同的樣式(使用唯一的樣式ID)並使if/else語句設置map.setMapTypeId。 –

相關問題