android javascript google之添加自定义overlay(文字+图片)
1.先定义myOverlay.js,此类为google.maps.OverlayView子类
var image_;var map_;var text_;var latLon_;var div_var marker;function myOverlay(map,image,text,latLon){this.map_=map;this.image_=image;this.text_=text;this.latLon_=latLon;marker=new google.maps.Marker({ position: latLon, map:map, icon:image, }); this.div_=null; google.maps.event.addListener(marker,'click',tapMarker); this.setMap(map);}myOverlay.prototype=new google.maps.OverlayView();myOverlay.prototype.onAdd=function(){ var div = document.createElement('DIV'); div.style.border = "none"; div.style.borderWidth = "0px"; div.style.position = "absolute"; var text = document.createElement('DIV'); text.style.width='50px'; text.style.height='20px'; text.style.color='red'; text.innerHTML=this.text_; div.appendChild(text); this.div_ = div; var panes = this.getPanes(); panes.overlayLayer.appendChild(div);}myOverlay.prototype.draw=function(){var overlayProjection = this.getProjection();var pixel = overlayProjection.fromLatLngToDivPixel(this.latLon_);var div = this.div_;div.style.left = (pixel.x-25)+'px';div.style.top = (pixel.y-50)+'px';div.style.width ='50px';div.style.height ='20px';}myOverlay.prototype.onRemove = function() { this.div_.parentNode.removeChild(this.div_); this.div_ = null;}// Note that the visibility property must be a string enclosed in quotesmyOverlay.prototype.hide = function() { if (this.div_) { this.div_.style.visibility = "hidden"; }}myOverlay.prototype.show = function() { if (this.div_) { this.div_.style.visibility = "visible"; }}myOverlay.prototype.toggle = function() { if (this.div_) { if (this.div_.style.visibility == "hidden") { this.show(); } else { this.hide(); } }}myOverlay.prototype.toggleDOM = function() { if (this.getMap()) { this.setMap(null); } else { this.setMap(this.map_); }}function tapMarker(){//调用java接口 window.javatojs.tapMarker();}
<!DOCTYPE html><html><head><meta name="viewport" content="initial-scale=1.0, user-scalable=no" /><style type="text/css"> html { height: 100%; width: 100% } body { height: 100%; width: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100%; width: 100% }</style><script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"/><script type="text/javascript" src="./js/myOverlay.js"/><script type="text/javascript"> var map; function initialize() { var latlng = new google.maps.LatLng(30.477343, 114.401870); var myOptions = { zoom: 17, center: latlng, disableDefaultUI: true, zoomControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var img='./imgs/taxi_booked.png'; var overlay = new myOverlay(map, img, '123456',latlng); }</script></head><body onload="initialize()"> <div id="map_canvas" style="width:100%; height:100%; width:100%;"></div></body></html>