キーは、Maps JavaScript API v3 の読み込み時に渡されます。API キーの生成の詳細
Google Maps API for Work をご利用の場合は、key パラメータではなく、client パラメータでクライアント ID を使用している可能性があります。クライアント ID は Maps JavaScript API v3 でも引き続きサポートされており、キーのアップグレード プロセスを行う必要はありません。
API の読み込み
コードに最初に行う必要がある変更は、API の読み込み方法に関するものです。v2 では、http://maps.google.com/maps へのリクエストを介して Maps JavaScript API を読み込みます。Maps JavaScript API v3 を読み込む場合は、次の変更を行う必要があります。
//maps.googleapis.com/maps/api/js から API を読み込む
file パラメータを削除します。
新しい v3 キーで key パラメータを更新します。Maps API for Work をご利用の場合は、client パラメータを使用する必要があります。
// 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 を使用して、これらのコントロールの表示方法をカスタマイズできます。
コントロール タイプの変更
v3 API では、control 型にいくつかの変更が導入されています。
v3 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 では、ストリートビューはデフォルトで有効になっています。地図にストリートビューのペグマン コントロールが表示され、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"]],["最終更新日 2025-01-10 UTC。"],[[["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"]]