我有以下代码,我正在使用带有叠加图像的Google地图。我在这张地图上用硬编码了一个标记。在我的页面中,我需要在“添加标记”按钮上添加标记,然后单击“获取纬度和经度”输入。如何在此按钮单击上将标记推到地图上。
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-map/3.0-rc1/jquery.ui.map.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<style>
#map {
height: 90%;
}
html, body {
height: 90%;
margin: 0;
padding: 0;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key= xxx"></script>
<script>
var overlay;
MapOverlay.prototype = new google.maps.OverlayView();
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 9.877717, lng: 79.694586},
mapTypeId: 'satellite'
});
var myLatLng = {lat: 9.8, lng: 79.9};
//adding a marker
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(9.71088992, 79.6855391),
new google.maps.LatLng(9.9351849, 80.048088));
var srcImage = 'file:///home/../abc.jpg';
overlay = new MapOverlay(bounds, srcImage, map);
}
function MapOverlay(bounds, image, map) {
........
}
MapOverlay.prototype.onAdd = function() {
.............
};
google.maps.event.addDomListener(window, 'load', initMap);
</script>
</head>
<body>
Latitude : <input type="text" placeholder="Latitude" id="lat"/>
Longitude : <input type="text" placeholder="Longitude" id="lng"/>
<button type="button" id="addMarkerBtnId">Add Marker</button>
<br/><br/>
<div id="map"></div>
答案 0 :(得分:2)
一种选择是使用google.maps.event.addDomListener
功能:
google.maps.event.addDomListener(document.getElementById('addMarkerBtnId'), 'click', function(evt) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(document.getElementById('lat').value),
lng: parseFloat(document.getElementById('lng').value)},
map: map
});
});
代码段
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: 9.877717,
lng: 79.694586
},
mapTypeId: 'satellite'
});
var myLatLng = {
lat: 9.8,
lng: 79.9
};
//adding a marker
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addDomListener(document.getElementById('addMarkerBtnId'), 'click', function(evt) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(document.getElementById('lat').value),
lng: parseFloat(document.getElementById('lng').value)
},
map: map
});
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
Latitude :
<input type="text" placeholder="Latitude" id="lat" value="9.877" /> Longitude :
<input type="text" placeholder="Longitude" id="lng" value="79.694" />
<button type="button" id="addMarkerBtnId">Add Marker</button>
<br/>
<br/>
<div id="map"></div>