谷歌地图,点击地图更改地图 - 在地图外

时间:2017-02-06 17:14:50

标签: google-maps events dom

我想在点击div(在地图之外)时更改地图(lat和lag)。

单击#map div时我已经工作了,但地图外的任何事件都没有被拾取。

这是我到目前为止所做的。

var map;

function initMap() {

  var mapDiv = document.getElementById('map');
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 52.9722222,
      lng: -3.1622222
    },
    disableDefaultUI: true,
    zoom: 17,
    mapTypeControlOptions: {
      mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
        'styled_map'
      ]
    }

  });

  google.maps.event.addDomListener(mapDiv, 'click', function() {
    window.alert('Map was clicked!');
  });

  var image = 'img/mapmarker.png';

  //Associate the styled map with the MapTypeId and set it to display.
  map.mapTypes.set('styled_map', styledMapType);
  map.setMapTypeId('styled_map');
  var marker = new google.maps.Marker({
    position: {
      lat: 52.9722222,
      lng: -3.1622222
    },
    map: map,
    icon: image,

  });

}

1 个答案:

答案 0 :(得分:0)

正在初始化的map变量是initMap函数的本地变量。您需要初始化全局版本:

var map;
function initMap() {
   var mapDiv = document.getElementById('map');
   // remove the var before map in this line:
   map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 52.9722222, lng: -3.1622222},

proof of concept fiddle

代码段



var map;

function initMap() {
  var mapDiv = document.getElementById('map');
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 52.9722222,
      lng: -3.1622222
    },
    disableDefaultUI: true,
    zoom: 17,
    mapTypeControlOptions: {
      mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
        'styled_map'
      ]
    }
  });

  google.maps.event.addDomListener(mapDiv, 'click', function() {
    window.alert('Map was clicked!');
  });

  var marker = new google.maps.Marker({
    position: {
      lat: 52.9722222,
      lng: -3.1622222
    },
    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>
<input type="button" value="Click Me!" onclick="map.setCenter({lat:52.97,lng:-3.16});map.setZoom(15);" />
<div id="map"></div>
&#13;
&#13;
&#13;