2017-04-30 10 views
0

私のコードは、ボタンをクリックしてGoogleマップ上のユーザーの現在の位置マーカーを見つけることです、ジオコード機能はアドレス情報を受信します。現在の場所のマーカーを見つける

どのように入力値ではなく、現在の位置の値をアドレスに使用できますか?

http://jsfiddle.net/razanrab/WppF6/253/

<body> 
    <div id="panel"> 
     <input id="city_country" type="textbox" value="Berlin, Germany"> 
     <input type="button" value="Geocode" onclick="codeAddress()"> 
    </div> 
    <div id="mapCanvas"></div> 
    <div id="infoPanel"> 
    <b>Marker status:</b> 
    <div id="markerStatus"><i>Click and drag the marker.</i></div> 
    <b>Current position:</b> 
    <div id="info"></div> 
    <b>Closest matching address:</b> 
    <div id="address"></div> 
    </div> 
</body> 


//js 

var geocoder; 
var map; 
var marker; 

codeAddress = function() { 
    geocoder = new google.maps.Geocoder(); 

    var address = document.getElementById('city_country').value; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     map = new google.maps.Map(document.getElementById('mapCanvas'), { 
    zoom: 16, 
      streetViewControl: false, 
      mapTypeControlOptions: { 
     style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, 
       mapTypeIds:[google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP] 
    }, 
    center: results[0].geometry.location, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

答えて

1

ユーザから現在位置を取得するためには、ジオロケーションAPIを使用する必要があります。

https://developers.google.com/maps/documentation/javascript/geolocation

if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function(position) { 
     var pos = { 
      lat: position.coords.latitude, 
      lng: position.coords.longitude 
     }; 

     infoWindow.setPosition(pos); 
     infoWindow.setContent('Location found.'); 
     infoWindow.open(map); 
     map.setCenter(pos); 
     }, function() { 
     handleLocationError(true, infoWindow, map.getCenter()); 
     }); 
    } else { 
     // Browser doesn't support Geolocation 
     handleLocationError(false, infoWindow, map.getCenter()); 
    } 
    } 

何を行うことができますが、マーカーの場所とジオコードクエリの結果の代わりに、マップの中心地として設定し、上記のPOSを変数を使用している:ここではドキュメントを参照してください。あなたのサンプルのように。これにより、テキストボックスからジオコードされた場所ではなく、ユーザーの場所の周囲に地図が表示されます。

あなたが提供したJSFiddleを私自身のコードと上記リンク先のジオロケーションサンプルから使用することができました。私はこれがあなたが探しているものだと信じています(JSFiddleが機能するためには独自のAPIキーを置く必要があります)。これはユーザーの位置を地理的に把握し、マーカーをドラッグしてアドレス情報を取得できるようにしますあなたのサンプルで。これにより、ユーザは、ジオコード]ボタンをクリックして、それでも同じ機能を持つことができるようになります:

https://jsfiddle.net/45z4841z/1/

私はこれが役に立てば幸い!

関連する問題