试图使用谷歌api v3从地址获取位置

时间:2012-04-23 22:47:39

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

我在我的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> 

我无法弄清楚这有什么不妥吗?

1 个答案:

答案 0 :(得分:4)

有多个错误,

  • 省略大括号
  • 首先初始化地图
  • geocode()需要GeocoderRequest-object作为参数

固定代码:

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);
        }

    });
}
相关问题