代码之家  ›  专栏  ›  技术社区  ›  alex

我可以知道,如果谷歌地图上没有找到一个位置时,使用这种懒惰的方法?

  •  1
  • alex  · 技术社区  · 15 年前

    我的JavaScript非常简单,我这样构建链接

    var googleMap = 'http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=' + address + '&ie=UTF8';
    

    当谷歌地图不知道 address ,它默认显示美国地图。不幸的是,我在澳大利亚。

    有没有办法用这个懒散的方法知道谷歌地图是否与地址不匹配,或者我可以默认显示澳大利亚?

    ... 或者我需要看看API吗?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Community CDub    5 年前

    用什么 maps.google.com.au ? 注意,参数可能有点不同。

    http://maps.google.com.au/maps?q=Melbourne

    http://maps.google.com.au/maps?q=Something-Garbage-That-Does-Not-Exist

    Maps API ,正如你所建议的。这样做很容易:

    <!DOCTYPE html>
    <html> 
    <head> 
       <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
       <title>Google Maps Geocoding Default Location</title> 
       <script src="http://maps.google.com/maps/api/js?sensor=false" 
               type="text/javascript"></script> 
    </head> 
    <body> 
       <div id="map" style="width: 400px; height: 300px;"></div> 
    
       <script type="text/javascript"> 
    
       var address = 'Melbourne, Australia';
    
       var map = new google.maps.Map(document.getElementById('map'), { 
           mapTypeId: google.maps.MapTypeId.TERRAIN,
           center: new google.maps.LatLng(-25.50, 135.00),
           zoom: 3
       });
    
       var geocoder = new google.maps.Geocoder();
    
       geocoder.geocode({
          'address': address
       }, 
       function(results, status) {
          if(status == google.maps.GeocoderStatus.OK) {
             new google.maps.Marker({
                position: results[0].geometry.location,
                map: map
             });
             map.setCenter(results[0].geometry.location);
          }
       });
    
       </script> 
    </body> 
    </html>
    

    截图:

    Google Maps Geocoding Default Location

    address = 'Something Garbage That Does Not Exist' :

    Google Maps Geocoding Default Location