且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为DIV添加背景图片,Google地图自定义控件

更新时间:2022-12-22 22:35:33




  1. 您的控件需要明确的高度和宽度 - 背景图片不会导致DIV增长以适合它们。

  2. 您使用的图片网址不存在(我获得404)。


如果您使用以下代码,您应该在左上角看到一个图像控件:

  var controlUI = document.createElement('DIV'); 
controlUI.style.cursor ='指针';
controlUI.style.backgroundImage =url(http://dummyimage.com/100x100);
controlUI.style.height ='100px';
controlUI.style.width ='100px';
controlUI.title ='点击将地图设置为首页';
myLocationControlDiv.appendChild(controlUI);

发布JSFiddle链接的出色工作 - 让这个问题很容易回答。


I am trying to create a image for google's custom controls. When I assign a background picture in a css, it breaks, otherwise it works.

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);


var myLocationControlDiv = document.createElement('DIV');

var controlUI = document.createElement('DIV');
//controlUI.style.borderWidth = '20px';
//controlUI.style.backgroundColor = 'black';
//controlUI.style.borderStyle = 'solid';
//controlUI.style.cursor = 'pointer';

//controlUI.style.backgroundImage = "url(/img/icons/pin.png)";

controlUI.title = 'Click to set the map to Home';
myLocationControlDiv.appendChild(controlUI);

map.controls[google.maps.ControlPosition.TOP_LEFT].push(controlUI);

You can also see it here: http://jsfiddle.net/k3Jjw/

Two simple problems:

  1. You need an explicit height and width on your control - background images don't cause the DIV to grow to fit them.

  2. The image URL you used does not exist (I get 404).

If you use the following code, you should see an image control in the top left:

var controlUI = document.createElement('DIV');
controlUI.style.cursor = 'pointer';
controlUI.style.backgroundImage = "url(http://dummyimage.com/100x100)";
controlUI.style.height = '100px';
controlUI.style.width = '100px';
controlUI.title = 'Click to set the map to Home';
myLocationControlDiv.appendChild(controlUI);

Great work posting the JSFiddle link - it made this question easy to answer.