脚本出错

时间:2017-03-09 20:08:48

标签: javascript

使用此脚本时,我得到添加标记未定义,但我似乎无法弄清楚问题。非常感谢任何纠正此错误的建议:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map" style="width: 700px; height: 400px"></div>
<script type="text/javascript">
 var latlng = new google.maps.LatLng(40.756, -73.986);
 var options = {
 center : latlng,
 zoom : 1,
 mapTypeId : google.maps.MapTypeId.ROADMAP
 };
 // Creating the map

 var map = new google.maps.Map(document.getElementById('map'), options);
 var geocoder = new google.maps.Geocoder();
 var marker= new google.maps.Marker(null);
 function AddMarker(address)
 {
  geocoder.geocode( {'address' : address}, function(results, status)
  {
   if (status == google.maps.GeocoderStatus.OK)
   {
    //map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker( {map : map,position : results[0].geometry.location });
    var infowindow;
    if (!infowindow)
    {
     infowindow = new google.maps.InfoWindow();
    }
    infowindow.setContent(address);
    google.maps.event.addListener(marker, 'click', function()
    {
     infowindow.open(map,marker);
    });
   }
  });
 }
</script>

2 个答案:

答案 0 :(得分:0)

  1. 看起来你已经调用了“添加标记”功能,而不是“AddMarker(target)”
  2. 你把infowindow称为恰当的声明。

答案 1 :(得分:0)

可能是你过早地调用AddMarker。

https://jsfiddle.net/c472zjqc/

&#13;
&#13;
var latlng = new google.maps.LatLng(40.756, -73.986);
var options = {
  center: latlng,
  zoom: 1,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map

var map = new google.maps.Map(document.getElementById('map'), options);
var geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker(null);

function AddMarker(address) {
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      //map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      var infowindow;
      if (!infowindow) {
        infowindow = new google.maps.InfoWindow();
      }
      infowindow.setContent(address);
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
      });
    }
  });
}

AddMarker('Wichita, KS');
map.setZoom(3);
&#13;
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map" style="width: 700px; height: 400px"></div>
&#13;
&#13;
&#13;