// Passes an overlay argument when clicking on a mapvarmap=newGMap2(document.getElementById('map'));map.setCenter(newGLatLng(-25.363882,131.044922),4);map.setUIToDefault();GEvent.addListener(map,'click',function(overlay,latlng){if(latlng){varmarker=newGMarker(latlng);map.addOverlay(marker);}});
// Passes only an event argumentvarmyOptions={center:newgoogle.maps.LatLng(-25.363882,131.044922),zoom:4,mapTypeId:google.maps.MapTypeId.ROADMAP};varmap=newgoogle.maps.Map(document.getElementById('map'),myOptions);google.maps.event.addListener(map,'click',function(event){varmarker=newgoogle.maps.Marker({position:event.latLng,map:map});});
控制項
Maps JavaScript API 會顯示 UI 控制項,讓使用者與地圖互動。您可以使用 API 自訂這些控制項的顯示方式。
varpoint=newGLatLng(180*Math.random()-90,360*Math.random()-180);varmap=newGMap2(document.getElementById("map"));map.setUIToDefault();map.setCenter(point);map.setMapType(G_HYBRID_MAP);map.getCurrentMapType().getMaxZoomAtLatLng(point,function(response){if(response.status){map.setZoom(response.zoom);}else{alert("Error in Max Zoom Service.");}});
varmyLatlng=newgoogle.maps.LatLng(180*Math.random()-90,360*Math.random()-180);varmap=newgoogle.maps.Map(document.getElementById("map"),{zoom:0,center:myLatlng,mapTypeId:google.maps.MapTypeId.HYBRID});varmaxZoomService=newgoogle.maps.MaxZoomService();maxZoomService.getMaxZoomAtLatLng(myLatlng,function(response){if(response.status==google.maps.MaxZoomStatus.OK){map.setZoom(response.zoom);}else{alert("Error in Max Zoom Service.");}});
加入 region 屬性可啟用區域代碼偏好設定,這等同於呼叫 setBaseCountryCode() 方法。
與 v2 回應相比,v3 中的地理編碼回應有很大差異。v3 API 會將 v2 使用的巢狀結構取代為更容易剖析的平面結構。此外,v3 回應更為詳細:每個結果都有幾個地址元件,可協助您進一步瞭解每個結果的解析度。
以下程式碼會擷取文字地址,並顯示地理編碼後的第一個結果:
vargeocoder=newGClientGeocoder();varinfoPanel;varmap;varAccuracyDescription=['Unknown accuracy','country level accuracy','region level accuracy','sub-region level accuracy','town level accuracy','post code level accuracy','street level accuracy','intersection level accuracy','address level accuracy','premise level accuracy',];functiongeocode_result_handler(response){if(!response||response.Status.code!=200){alert('Geocoding failed. '+response.Status.code);}else{varbounds=newGLatLngBounds(newGLatLng(response.Placemark[0].ExtendedData.LatLonBox.south,response.Placemark[0].ExtendedData.LatLonBox.west),newGLatLng(response.Placemark[0].ExtendedData.LatLonBox.north,response.Placemark[0].ExtendedData.LatLonBox.east));map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));varlatlng=newGLatLng(response.Placemark[0].Point.coordinates[1],response.Placemark[0].Point.coordinates[0]);infoPanel.innerHTML+='<p>1st result is <em>'+// No info about location typeresponse.Placemark[0].address+'</em> of <em>'+AccuracyDescription[response.Placemark[0].AddressDetails.Accuracy]+'</em> at <tt>'+latlng+'</tt></p>';varmarker_title=response.Placemark[0].address+' at '+latlng;map.clearOverlays();varmarker=marker=newGMarker(latlng,{'title':marker_title});map.addOverlay(marker);}}functiongeocode_address(){varaddress=document.getElementById('input-text').value;infoPanel.innerHTML='<p>Original address: '+address+'</p>';geocoder.getLocations(address,geocode_result_handler);}functioninitialize(){map=newGMap2(document.getElementById('map'));map.setCenter(newGLatLng(38,15),2);map.setUIToDefault();infoPanel=document.getElementById('info-panel');}
vargeocoder=newgoogle.maps.Geocoder();varinfoPanel;varmap;varmarker;functiongeocode_result_handler(result,status){if(status!=google.maps.GeocoderStatus.OK){alert('Geocoding failed. '+status);}else{map.fitBounds(result[0].geometry.viewport);infoPanel.innerHTML+='<p>1st result for geocoding is <em>'+result[0].geometry.location_type.toLowerCase()+'</em> to <em>'+result[0].formatted_address+'</em> of types <em>'+result[0].types.join('</em>, <em>').replace(/_/,' ')+'</em> at <tt>'+result[0].geometry.location+'</tt></p>';varmarker_title=result[0].formatted_address+' at '+latlng;if(marker){marker.setPosition(result[0].geometry.location);marker.setTitle(marker_title);}else{marker=newgoogle.maps.Marker({position:result[0].geometry.location,title:marker_title,map:map});}}}functiongeocode_address(){varaddress=document.getElementById('input-text').value;infoPanel.innerHTML='<p>Original address: '+address+'</p>';geocoder.geocode({'address':address},geocode_result_handler);}functioninitialize(){map=newgoogle.maps.Map(document.getElementById('map'),{center:newgoogle.maps.LatLng(38,15),zoom:2,mapTypeId:google.maps.MapTypeId.HYBRID});infoPanel=document.getElementById('info-panel');}
functioninitialize(){varfenwayPark=newGLatLng(42.345573,-71.098326);panoramaOptions={latlng:fenwayPark,pov:{heading:35,pitch:5,zoom:1}};varpanorama=newGStreetviewPanorama(document.getElementById('pano'),panoramaOptions);GEvent.addListener(myPano,"error",handleNoFlash);}functionhandleNoFlash(errorCode){if(errorCode==FLASH_UNAVAILABLE){alert('Error: Your browser does not support Flash');return;}}
在第 3 版中,街景服務是預設啟用的服務。地圖會顯示街景服務衣夾人控制項,而 API 會重複使用地圖 div 來顯示街景服務全景。以下程式碼說明如何模擬 v2 行為,將街景服務全景分隔至不同的 div。
varmarker;varpanoClient=newGStreetviewClient();functioninitialize(){if(GBrowserIsCompatible()){varmyPano=newGStreetviewPanorama(document.getElementById('pano'));GEvent.addListener(myPano,'error',handleNoFlash);varmap=newGMap2(document.getElementById('map'));map.setCenter(newGLatLng(42.345573,-71.098326),16);map.setUIToDefault();GEvent.addListener(map,'click',function(overlay,latlng){if(marker){marker.setLatLng(latlng);}else{marker=newGMarker(latlng);map.addOverlay(marker);}varnearestPano=panoClient.getNearestPanorama(latlng,processSVData);});functionprocessSVData(panoData){if(panoData.code!=200){alert("Panorama data not found for this location.");}varlatlng=marker.getLatLng();vardLat=latlng.latRadians()-panoData.location.latlng.latRadians();vardLon=latlng.lngRadians()-panoData.location.latlng.lngRadians();vary=Math.sin(dLon)*Math.cos(latlng.latRadians());varx=Math.cos(panoData.location.latlng.latRadians())*Math.sin(latlng.latRadians())-Math.sin(panoData.location.latlng.latRadians())*Math.cos(latlng.latRadians())*Math.cos(dLon);varbearing=Math.atan2(y,x)*180/Math.PI;myPano.setLocationAndPOV(panoData.location.latlng,{yaw:bearing});}functionhandleNoFlash(errorCode){if(errorCode==FLASH_UNAVAILABLE){alert('Error: Your browser does not support Flash');return;}}}}
// Load the API with libraries=geometryvarmap;varmarker;varpanorama;varsv=newgoogle.maps.StreetViewService();functionradians(degrees){returnMath.PI*degrees/180.0};functioninitialize(){panorama=newgoogle.maps.StreetViewPanorama(document.getElementById("pano"));map=newgoogle.maps.Map(document.getElementById('map'),{center:newgoogle.maps.LatLng(42.345573,-71.098326),mapTypeId:google.maps.MapTypeId.ROADMAP,zoom:16});google.maps.event.addListener(map,'click',function(event){if(!marker){marker=newgoogle.maps.Marker({position:event.latLng,map:map});}else{marker.setPosition(event.latLng);}sv.getPanoramaByLocation(event.latLng,50,processSVData);});}functionprocessSVData(panoData,status){if(status==google.maps.StreetViewStatus.OK){alert("Panorama data not found for this location.");}varbearing=google.maps.geometry.spherical.computeHeading(panoData.location.latLng,marker.getPosition());panorama.setPano(panoData.location.pano);panorama.setPov({heading:bearing,pitch:0,zoom:1});panorama.setVisible(true);marker.setMap(panorama);}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-03-21 (世界標準時間)。"],[[["Google Maps API v2 is retired and websites using it must migrate to v3."],["Migration involves obtaining a new API key, updating the API loading code, and adapting application code to v3's namespace and objects."],["V3 offers numerous improvements, including enhanced performance, modernized client-side usage limits, wider browser support, new features, and updated services."],["Key code changes include using the `google.maps` namespace, replacing obsolete methods, and adopting v3's approach to controls, overlays, and services."],["Developers should consult the provided v3 documentation and resources for detailed guidance and code examples during migration."]]],["The v2 Maps JavaScript API is discontinued, requiring migration to v3. Key actions include obtaining a new API key and updating the API loading code. Code must be updated to use the `google.maps.*` namespace, removing obsolete methods. V3 offers a lighter core, improved performance, new features like styled maps and enhanced directions, multiple InfoWindows, and modern browser support. V3 also changes the way the controls, overlays, Geocoding, Directions and Streetview work, requiring code adaptations.\n"]]