【问题标题】:trying to get location from address using google api v3尝试使用 google api v3 从地址获取位置
【发布时间】:2012-05-04 14:01:12
【问题描述】:

我的 html 中有这个 javascript,我想要在这里做的是在给定位置的情况下获取地图表示

<script type="text/javascript">
var geocoder;
var map;
function getmaploc() {
    geocoder = new google.maps.Geocoder();
    var myOptions = {
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    geocoder.geocode( 'cairo', 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
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    });
}
</script>

<body onload="getmaploc()">
  <div id="map_canvas"  style="width: 320px; height: 480px;"></div>
</body> 

我不知道这有什么问题?有帮助吗?

【问题讨论】:

  • 请格式化您的代码,很多人(包括我)不会阅读格式不正确的代码
  • 修复了我很抱歉我是stackoverflow的新手
  • 为您重新格式化,您的 fix 仍然不是很可读。这里还有一个提示:“它不起作用”没有错误消息会让其他人更难提供帮助。
  • 非常感谢,现在代码看起来更干净了:D 问题已修复

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


【解决方案1】:

有多个错误,

  • 省略的大括号
  • 先初始化地图
  • geocode() 需要一个 GeocoderRequest 对象作为参数

固定代码:

var geocoder;
var map;
function getmaploc() {
    geocoder = new google.maps.Geocoder();
    var myOptions = {
        zoom : 8,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    geocoder.geocode({
        address : 'cairo'
    }, function(results, status) {
        console.log(results);
        if(status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            new google.maps.Marker({
                map : map,
                position : results[0].geometry.location
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }

    });
}

【讨论】:

  • 请不要抱怨我的缩进,我喜欢它^^
  • 非常感谢 Dr.Molle 解决了这个问题
猜你喜欢
  • 1970-01-01
  • 2011-07-08
  • 2011-03-19
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
相关资源
最近更新 更多