如何在此代码中添加地理位置?

时间:2014-02-05 15:51:33

标签: javascript google-maps google-maps-api-3 geolocation marker

我目前正在尝试将地理位置功能添加到以下代码中:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var marker;
var infowindow;

function initialize() {
  var latlng = new google.maps.LatLng(51.507059, -0.122631);
  var options = {
    zoom: 14,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map-canvas"), options);
  var html = &quot;<table/>&quot; +
             &quot;<tr><td>Name:</td><td><input id='name' type='text'/></td></tr>&quot; +
      &quot;<tr><td><br/>Description:</td><td><input id='description' type='text'/></td></tr>&quot; +
      &quot;<tr><td/><td><br/><center><input onclick='saveData()' type='button' value='Save &amp; Close'/></center></td></tr>&quot;;
infowindow = new google.maps.InfoWindow({
 content: html
});

google.maps.event.addListener(map, "click", function(event) {
    marker = new google.maps.Marker({
      position: event.latLng,
      map: map
    });
    google.maps.event.addListener(marker, "click", function() {
      infowindow.open(map, marker);
    });
});
}

google.maps.event.addDomListener(window, &#39;load&#39;, initialize);

</script>

地理位置代码:

// HTML5 geolocation
if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
    var pos = new google.maps.LatLng(position.coords.latitude,
                                   position.coords.longitude);

    var infowindow = new google.maps.InfoWindow({
        map: map,
        position: pos,
        content: 'Location found using HTML5.'
    });

    map.setCenter(pos);
    }, function() {
    handleNoGeolocation(true);
    });
} else {
    // Browser doesn't support Geolocation
    handleNoGeolocation(false);
}
}

function handleNoGeolocation(errorFlag) {
if (errorFlag) {
    var content = 'Error: Locations services failed.';
} else {
    var content = 'Error: Your browser doesn\'t support geolocation.';
}

var options = {
    map: map,
    position: new google.maps.LatLng(51.507059, -0.122631),
    content: content
};

var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}

但是,当我尝试合并初始化函数时,我收到错误'无法读取属性'_ e3 '未定义。如果我将函数分开,程序就会忽略地理位置代码。所以,我被困住了,并希望有人可以帮助我。万分感谢!

注意:我在https://developers.google.com/maps/尝试了所有相关内容,并检查了本网站上所有非常相似的问题 - 这不是重复的帖子。另外,请忽略我在JavaScript中使用HTML字符代码 - 这是在HTML(webdata)内部的JavaScript(代码)内部获取HTML(infowindow)的唯一方法。

0 个答案:

没有答案