【问题标题】:How to overlay a <div> object and a raster Image如何叠加 <div> 对象和光栅图像
【发布时间】:2018-01-23 08:14:56
【问题描述】:

我正在尝试按此层顺序从上到下覆盖一些对象:

  1. 信息窗口
  2. PNG 图片
  3. 谷歌地图

我确实覆盖了第 2 层和第 3 层。但是,我无法在上面显示Info Window

我调试了修改后的代码。当我添加autocomplete变量时发生这种情况,无法显示覆盖的PNG图像。

autocomplete变量在下面的当前代码sn-p中被我标记为注释)

请问您有什么想法吗?谢谢之前

我要叠加的第二层图像是:

我的代码是:

// This example creates a custom overlay called USGSOverlay, containing
// a U.S. Geological Survey (USGS) image of the relevant area on the map.

// Set the custom overlay object's prototype to a new instance
// of OverlayView. In effect, this will subclass the overlay class therefore
// it's simpler to load the API synchronously, using
// google.maps.event.addDomListener().
// Note that we set the prototype to an instance, rather than the
// parent class itself, because we do not wish to modify the parent class.

var overlay;
USGSOverlay.prototype = new google.maps.OverlayView();

// Initialize the map and the custom overlay.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {
      lat: -7.782886,
      lng: 110.367037
    },
    mapTypeId: 'satellite'
  });

  var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-7.9161700000000002, 110.1243099999999941),
    new google.maps.LatLng(-7.3161699999999996, 110.7243100000000027));

  // The photograph is courtesy of the U.S. Geological Survey.
  var srcImage = 'https://i.stack.imgur.com/vR3Rz.png';

  var input = document.getElementById('pac-input');
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  // Variable untuk Location Seach Bar

  var infowindow = new google.maps.InfoWindow();
  var infowindowContent = document.getElementById('infowindow-content');
  infowindow.setContent(infowindowContent);
  // Variable untuk kotak keterangan lokasi

  var marker = new google.maps.Marker({
    map: map
  });

  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

  /*
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);
	
  autocomplete.addListener('place_changed', function() {
  	infowindow.close();
  	var place = autocomplete.getPlace();
  	
  	if (!place.geometry) {
  		return;
  	}

  	if (place.geometry.viewport) {
  		map.fitBounds(place.geometry.viewport); 
  	} else {
  		map.setCenter(place.geometry.location);
  		map.setZoom(17);
  	}

  	// Set the position of the marker using the place ID and location.
  	marker.setPlace({
  		placeId: place.place_id,
  		location: place.geometry.location
  	});
  	
  	marker.setVisible(true);

  	infowindowContent.children['place-name'].textContent = place.name;
  	//infowindowContent.children['place-id'].textContent = place.place_id;//Script penampil Place ID tidak perlu dijalankan
  	infowindowContent.children['place-address'].textContent = place.formatted_address;
  	infowindow.open(map, marker);
  });
  */

  // The custom USGSOverlay object contains the USGS image,
  // the bounds of the image, and a reference to the map.
  overlay = new USGSOverlay(bounds, srcImage, map);

}

/** @constructor */
function USGSOverlay(bounds, image, map) {
  // Initialize all properties.
  this.bounds_ = bounds;
  this.image_ = image;
  this.map_ = map;

  // Define a property to hold the image's div. We'll
  // actually create this div upon receipt of the onAdd()
  // method so we'll leave it null for now.
  this.div_ = null;

  // Explicitly call setMap on this overlay.
  this.setMap(map);
}

/**
 * onAdd is called when the map's panes are ready and the overlay has been
 * added to the map.
 */
USGSOverlay.prototype.onAdd = function() {
  var div = document.createElement('div');
  div.style.borderStyle = 'none';
  div.style.borderWidth = '0px';
  div.style.position = 'absolute';

  // Create the img element and attach it to the div.
  var img = document.createElement('img');
  img.src = this.image_;
  img.style.width = '100%';
  img.style.height = '100%';
  img.style.position = 'absolute';
  div.appendChild(img);

  this.div_ = div;

  // Add the element to the "overlayLayer" pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
};

USGSOverlay.prototype.draw = function() {
  // We use the south-west and north-east
  // coordinates of the overlay to peg it to the correct position and size.
  // To do this, we need to retrieve the projection from the overlay.
  var overlayProjection = this.getProjection();

  // Retrieve the south-west and north-east coordinates of this overlay
  // in LatLngs and convert them to pixel coordinates.
  // We'll use these coordinates to resize the div.
  var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Resize the image's div to fit the indicated dimensions.
  var div = this.div_;
  div.style.left = sw.x + 'px';
  div.style.top = ne.y + 'px';
  div.style.width = (ne.x - sw.x) + 'px';
  div.style.height = (sw.y - ne.y) + 'px';
};

// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
USGSOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
};

google.maps.event.addDomListener(window, 'load', initMap);
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.controls {
  background-color: #fff;
  border-radius: 2px;
  border: 1px solid transparent;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  height: 29px;
  margin-left: 17px;
  margin-top: 10px;
  outline: none;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 400px;
}

.controls:focus {
  border-color: #4d90fe;
}

.title {
  font-weight: bold;
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">

  <title>Thank you for looking around to this code</title>

</head>

<body>
  <div id="map">
  </div>
  <!-- Menampilkan Pigura Frame Google Maps API -->

  <input id="pac-input" class="controls" type="text" placeholder="Enter a location">
  <!-- Menampilkan Location Search Bar -->

  <div id="infowindow-content">
    <span id="place-name" class="title"></span><br>
    <span id="place-id"></span><br>
    <span id="place-address"></span>
  </div>
  <!-- Menampilkan kotak keterangan lokasi -->

  <script src="https://maps.googleapis.com/maps/api/js?key=MY-API-KEY&libraries=places&callback=initMap">
  </script>
  <!-- Java script for displaying Google Maps API-->
  <!-- The script was adopted from Google Developer (2018) -->
  <!-- You need Google Maps API Key to display the map on your web -->

  <!-- Code References
	SitePoint, HTML Template
		https://www.sitepoint.com/a-basic-html5-template/
		accessed on 12 January 2018
	HTML5 Doctor, CSS Reset
		http://html5doctor.com/html-5-reset-stylesheet/
		accessed on 11 January 2018
	Google Developers, Adding a Google Maps API
		https://developers.google.com/maps/documentation/javascript/adding-a-google-map
		accessed on 11 January 2018
	Google Developers, Google Maps API PlaceID Finder
		https://developers.google.com/maps/documentation/javascript/adding-a-google-map
		accessed on 15 January 2018
	-->

</body>

</html>

【问题讨论】:

  • 注意: Web 程序员需要注意 Web 浏览器中的“javascript 控制台”。它将向您显示与您的脚本相关的任何错误(如果有)。如何为任何浏览器打开“javascript控制台”,您可以在此处阅读webmasters.stackexchange.com/questions/8525/…
  • 此外: 如果您将 javascript 合并到 HTML(单个文件)中,请不要在您的 overlayinitmap 脚本之后调用您的搜索脚本。我猜这个问题与脚本执行问题有关。

标签: javascript html google-maps-api-3


【解决方案1】:

发布的代码出现错误:Uncaught InvalidValueError: initMap is not a function。从 API 包含中移除回调参数,更改:

<script src="https://maps.googleapis.com/maps/api/js?key=MY-API-KEY&libraries=places&callback=initMap">
</script>

收件人:

<script src="https://maps.googleapis.com/maps/api/js?key=MY-API-KEY&libraries=places">
</script>

工作代码 sn-p:

// This example creates a custom overlay called USGSOverlay, containing
// a U.S. Geological Survey (USGS) image of the relevant area on the map.

// Set the custom overlay object's prototype to a new instance
// of OverlayView. In effect, this will subclass the overlay class therefore
// it's simpler to load the API synchronously, using
// google.maps.event.addDomListener().
// Note that we set the prototype to an instance, rather than the
// parent class itself, because we do not wish to modify the parent class.

var overlay;
USGSOverlay.prototype = new google.maps.OverlayView();

// Initialize the map and the custom overlay.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {
      lat: -7.782886,
      lng: 110.367037
    },
    mapTypeId: 'satellite'
  });

  var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-7.9161700000000002, 110.1243099999999941),
    new google.maps.LatLng(-7.3161699999999996, 110.7243100000000027));

  // The photograph is courtesy of the U.S. Geological Survey.
  var srcImage = 'https://i.stack.imgur.com/vR3Rz.png';

  var input = document.getElementById('pac-input');
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  // Variable untuk Location Seach Bar

  var infowindow = new google.maps.InfoWindow();
  var infowindowContent = document.getElementById('infowindow-content');
  infowindow.setContent(infowindowContent);
  // Variable untuk kotak keterangan lokasi

  var marker = new google.maps.Marker({
    map: map
  });

  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });


  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);

  autocomplete.addListener('place_changed', function() {
    infowindow.close();
    var place = autocomplete.getPlace();

    if (!place.geometry) {
      return;
    }

    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);
    }

    // Set the position of the marker using the place ID and location.
    marker.setPlace({
      placeId: place.place_id,
      location: place.geometry.location
    });

    marker.setVisible(true);

    infowindowContent.children['place-name'].textContent = place.name;
    //infowindowContent.children['place-id'].textContent = place.place_id;//Script penampil Place ID tidak perlu dijalankan
    infowindowContent.children['place-address'].textContent = place.formatted_address;
    infowindow.open(map, marker);
  });


  // The custom USGSOverlay object contains the USGS image,
  // the bounds of the image, and a reference to the map.
  overlay = new USGSOverlay(bounds, srcImage, map);

}

/** @constructor */
function USGSOverlay(bounds, image, map) {
  // Initialize all properties.
  this.bounds_ = bounds;
  this.image_ = image;
  this.map_ = map;

  // Define a property to hold the image's div. We'll
  // actually create this div upon receipt of the onAdd()
  // method so we'll leave it null for now.
  this.div_ = null;

  // Explicitly call setMap on this overlay.
  this.setMap(map);
}

/**
 * onAdd is called when the map's panes are ready and the overlay has been
 * added to the map.
 */
USGSOverlay.prototype.onAdd = function() {
  var div = document.createElement('div');
  div.style.borderStyle = 'none';
  div.style.borderWidth = '0px';
  div.style.position = 'absolute';

  // Create the img element and attach it to the div.
  var img = document.createElement('img');
  img.src = this.image_;
  img.style.width = '100%';
  img.style.height = '100%';
  img.style.position = 'absolute';
  div.appendChild(img);

  this.div_ = div;

  // Add the element to the "overlayLayer" pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
};

USGSOverlay.prototype.draw = function() {
  // We use the south-west and north-east
  // coordinates of the overlay to peg it to the correct position and size.
  // To do this, we need to retrieve the projection from the overlay.
  var overlayProjection = this.getProjection();

  // Retrieve the south-west and north-east coordinates of this overlay
  // in LatLngs and convert them to pixel coordinates.
  // We'll use these coordinates to resize the div.
  var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Resize the image's div to fit the indicated dimensions.
  var div = this.div_;
  div.style.left = sw.x + 'px';
  div.style.top = ne.y + 'px';
  div.style.width = (ne.x - sw.x) + 'px';
  div.style.height = (sw.y - ne.y) + 'px';
};

// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
USGSOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
};

google.maps.event.addDomListener(window, 'load', initMap);
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.controls {
  background-color: #fff;
  border-radius: 2px;
  border: 1px solid transparent;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  height: 29px;
  margin-left: 17px;
  margin-top: 10px;
  outline: none;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 400px;
}

.controls:focus {
  border-color: #4d90fe;
}

.title {
  font-weight: bold;
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">

  <title>Thank you for looking around to this code</title>

</head>

<body>
  <div id="map">
  </div>
  <!-- Menampilkan Pigura Frame Google Maps API -->

  <input id="pac-input" class="controls" type="text" placeholder="Enter a location">
  <!-- Menampilkan Location Search Bar -->

  <div id="infowindow-content">
    <span id="place-name" class="title"></span><br>
    <span id="place-id"></span><br>
    <span id="place-address"></span>
  </div>
  <!-- Menampilkan kotak keterangan lokasi -->

  <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
  </script>
  <!-- Java script for displaying Google Maps API-->
  <!-- The script was adopted from Google Developer (2018) -->
  <!-- You need Google Maps API Key to display the map on your web -->

  <!-- Code References
    SitePoint, HTML Template
        https://www.sitepoint.com/a-basic-html5-template/
        accessed on 12 January 2018
    HTML5 Doctor, CSS Reset
        http://html5doctor.com/html-5-reset-stylesheet/
        accessed on 11 January 2018
    Google Developers, Adding a Google Maps API
        https://developers.google.com/maps/documentation/javascript/adding-a-google-map
        accessed on 11 January 2018
    Google Developers, Google Maps API PlaceID Finder
        https://developers.google.com/maps/documentation/javascript/adding-a-google-map
        accessed on 15 January 2018
    -->

</body>

</html>

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多