我如何自定义google maps api(v3
javascript)缩放按钮到我自己的图像.
解决方法
我晚会在晚会,但这是我的两分钱.
你基本上有两个选择:
选项1:您可以使用HTML / CSS自己创建控件,然后您可以使用位置绝对或类似方式将地图放置到正确的位置.即使这在生产中有效,但我不喜欢这样做,因为您的HTML / CSS元素不会与显示地图同时加载.此外,您将HTML / CSS代码分离到控件中,因此难以在不同的页面重复使用相同的地图.例如“我忘了添加控件吗?”
选项2:您创建了一个看起来和感觉您喜欢的缩放控制器的a custom control.以下是关于这一点的代码.
简而言之,您需要先禁用正常的UI控制器:
var mapOptions = { zoom: 12,center: chicago,/* Disabling default UI widgets */ disableDefaultUI: true // <-- see this line }
然后你只需创建控制器并使用它.
HTML:
... <div id="map-canvas"></div> ...
CSS:
html,body,#map-canvas { height: 100%; margin: 0px; padding: 0px; }
JavaScript的:
var map; var chicago = new google.maps.LatLng(41.850033,-87.6500523); /** * The ZoomControl adds +/- button for the map * */ function ZoomControl(controlDiv,map) { // Creating divs & styles for custom zoom control controlDiv.style.padding = '5px'; // Set CSS for the control wrapper var controlWrapper = document.createElement('div'); controlWrapper.style.backgroundColor = 'white'; controlWrapper.style.borderStyle = 'solid'; controlWrapper.style.borderColor = 'gray'; controlWrapper.style.borderWidth = '1px'; controlWrapper.style.cursor = 'pointer'; controlWrapper.style.textAlign = 'center'; controlWrapper.style.width = '32px'; controlWrapper.style.height = '64px'; controlDiv.appendChild(controlWrapper); // Set CSS for the zoomIn var zoomInButton = document.createElement('div'); zoomInButton.style.width = '32px'; zoomInButton.style.height = '32px'; /* Change this to be the .png image you want to use */ zoomInButton.style.backgroundImage = 'url("http://placehold.it/32/00ff00")'; controlWrapper.appendChild(zoomInButton); // Set CSS for the zoomOut var zoomOutButton = document.createElement('div'); zoomOutButton.style.width = '32px'; zoomOutButton.style.height = '32px'; /* Change this to be the .png image you want to use */ zoomOutButton.style.backgroundImage = 'url("http://placehold.it/32/0000ff")'; controlWrapper.appendChild(zoomOutButton); // Setup the click event listener - zoomIn google.maps.event.addDomListener(zoomInButton,'click',function() { map.setZoom(map.getZoom() + 1); }); // Setup the click event listener - zoomOut google.maps.event.addDomListener(zoomOutButton,function() { map.setZoom(map.getZoom() - 1); }); } function initialize() { var mapDiv = document.getElementById('map-canvas'); var mapOptions = { zoom: 12,/* Disabling default UI widgets */ disableDefaultUI: true } map = new google.maps.Map(mapDiv,mapOptions); // Create the DIV to hold the control and call the ZoomControl() constructor // passing in this DIV. var zoomControlDiv = document.createElement('div'); var zoomControl = new ZoomControl(zoomControlDiv,map); zoomControlDiv.index = 1; map.controls[google.maps.ControlPosition.TOP_LEFT].push(zoomControlDiv); } initialize();
注意:此代码不包含任何花哨的图标,只是占位符.因此,您可能需要调整以适应您的需要.此外,请记住添加HTML5普通标签和脚本包含为google maps api v3 javascript.我只添加了< div id =“map-canvas”>< / div>因为需要休息的身体是很明显的.
看到它的生活:Here is working jsfiddle example
干杯.