// 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 会显示界面控件,以便用户与您的地图互动。您可以使用该 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() 方法。
v3 中的地理编码响应与 v2 响应截然不同。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;}}
您可以通过 v3 中的 StreetViewService 对象或 v2 中的类似 GStreetviewClient 对象直接访问街景数据。这两个 API 都提供了类似的接口,用于检索或检查街景数据的可用性,并允许按位置或全景图片 ID 进行搜索。
默认情况下,v3 中街景视图处于启用状态。地图上会显示街景小人控件,并且该 API 会重复使用地图 div 来显示街景全景图片。以下代码展示了如何通过将街景全景图分隔到单独的 div 中来模拟 v2 行为。
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"]],["最后更新时间 (UTC):2025-01-10。"],[[["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"]]