trying to get location from address using google api v3

心不动则不痛 提交于 2020-01-04 14:12:47

问题


I have this javascript in my html what i want to do here is to get a map representation given the location

<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> 

I cant figure out whats wrong with this any help??


回答1:


There are multiple errors,

  • a omitted brace
  • initialize the map first
  • geocode() expects a GeocoderRequest-object as argument

fixed code:

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

    });
}


来源:https://stackoverflow.com/questions/10289346/trying-to-get-location-from-address-using-google-api-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!