1 //这个构造器能获取此对象到地图盒子的绝对距离 2 function ContextMenu(map, options){ 3 var obj = {} 4 this.setMap(map); 5 this.map_=map; 6 this.mapDiv_=map.getDiv(); 7 8 } 9 10 ContextMenu.prototype=new google.maps.OverlayView(); 11 12 ContextMenu.prototype.draw=function(){ 13 if(this.isVisible_){ 14 var mapSize=new google.maps.Size(this.mapDiv_.offsetWidth, this.mapDiv_.offsetHeight); 15 var menuSize=new google.maps.Size(this.menu_.offsetWidth, this.menu_.offsetHeight); 16 var mousePosition=this.getProjection().fromLatLngToDivPixel(this.position_); 17 18 var left=mousePosition.x; 19 var top=mousePosition.y; 20 21 if(mousePosition.x>mapSize.width-menuSize.width-this.pixelOffset.x){ 22 left=left-menuSize.width-this.pixelOffset.x; 23 } else { 24 left+=this.pixelOffset.x; 25 } 26 27 if(mousePosition.y>mapSize.height-menuSize.height-this.pixelOffset.y){ 28 top=top-menuSize.height-this.pixelOffset.y; 29 } else { 30 top+=this.pixelOffset.y; 31 } 32 33 this.menu_.style.left=left+'px'; 34 this.menu_.style.top=top+'px'; 35 } 36 }; 37 38 39 40 //新的构造器对象 41 var map_context_menu=new ContextMenu(map); 42 43 map.addListener('rightclick',function(e){ 44 var position=map_context_menu.getProjection().fromLatLngToDivPixel(e.latLng); //得到的是点击点距离地图的绝对距离 45 }); 46 marker.addListener('rightclick',function(e){ 47 var position=map_context_menu.getProjection().fromLatLngToDivPixel(e.latLng); 48 });
注,以上方法当拖动地图时,菜单的位置会出问题;;
重新找到了方法将经纬度转为{x:111, y:222} 坐标
1 //将谷歌地图的经纬度转为对象像素 2 var fromLatLngToPixel=function(position,map){ 3 var scale = Math.pow(2, map.getZoom()); 4 var proj = map.getProjection(); 5 var bounds = map.getBounds(); 6 var nw = proj.fromLatLngToPoint( 7 new google.maps.LatLng( 8 bounds.getNorthEast().lat(), 9 bounds.getSouthWest().lng() 10 ) 11 ); 12 var point = proj.fromLatLngToPoint(position); 13 return new google.maps.Point( 14 Math.floor((point.x - nw.x) * scale), 15 Math.floor((point.y - nw.y) * scale) 16 ); 17 //{x: 17, y: 38} 18 } 19 20 //将谷歌地图的对象像素转为经纬度 21 var fromPixelToLatLng=function(pixel,map){ 22 var scale = Math.pow(2, Map.getZoom()); 23 var proj = Map.getProjection(); 24 var bounds = Map.getBounds(); 25 var nw = proj.fromLatLngToPoint( 26 new google.maps.LatLng( 27 bounds.getNorthEast().lat(), 28 bounds.getSouthWest().lng() 29 ) 30 ); 31 var point = new google.maps.Point(); 32 point.x = pixel.x / scale + nw.x; 33 point.y = pixel.y / scale + nw.y; 34 return proj.fromPointToLatLng(point); 35 }