0

데이터베이스에 위치가 저장되어 있으며 Google지도 (API v3)에 각 위치 (JS와 면도날의 혼합)마다 마커가 표시됩니다.Google지도 지오 코드 잘못된 주소 표시

내가 사용하는 코드는 StackOverFlow에서 이틀 전 a question I asked입니다. 문제의 두 개의 주소는 다음과 같습니다

  1. 6-7 홀 장소, 스폴딩, PE11, 삼상, 영국
  2. 29 유니온 스트리트, 버밍엄, B2 4LR, 영국

이 주소는 완벽하게 on here을 보여 . 하지만 내 사이트 (localhost 현재)에서 그들을 시도 할 때, 하나는 샌프란 시스코와 다른 루이지애나 미국에 나타납니다 !! 여기

는 (일부 C 번호는/면도기가 혼합 참고) 내가 사용 자바 스크립트 코드 :

<script type="text/javascript"> 

    // Get the map container node. 
    var mapContainer = $("#myMap"); 
    var geocoder = new google.maps.Geocoder(); 

    // Create the new Goole map controller using our 
    // map (pass in the actual DOM object). Center it 
    // above the first Geolocated IP address. 
    map = new google.maps.Map(
     mapContainer[ 0 ], 
     { 
      zoom: 11, 
      center: new google.maps.LatLng(
       51.51121, 
       -0.11982 
      ), 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 
    ); 


    // I add a marker to the map using the given latitude 
    // and longitude location. 
    function addMarker(latitude, longitude, label) { 
     var myLatlng = new google.maps.LatLng(latitude, longitude); 
     // Create our "tiny" marker icon 
     var iconImage = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png'; 

     // Create the marker - this will automatically place it 
     // on the existing Google map (that we pass-in). 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: new google.maps.LatLng(
       latitude, 
       longitude 
      ), 
      title: (label || ""), 
      icon: iconImage, 
      center: myLatlng, 
      zoom: 10 
     }); 



     // Return the new marker reference. 
     return(marker); 
    } 

    // I update the marker's position and label. 
    function updateMarker(marker, latitude, longitude, label){ 
     // Update the position. 
     marker.setPosition(
      new google.maps.LatLng(
       latitude, 
       longitude 
      ) 
     ); 

     // Update the title if it was provided. 
     if (label){ 
      marker.setTitle(label); 
     } 
    } 

    function placeMarkerForAddress(address, city, postcode, country) { 
     geocoder.geocode({ 'address': address}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       var marker = new google.maps.Marker({ 
        map: map, 
        position: results[0].geometry.location, 
        title: address + ', ' + city + ', ' + postcode + ', ' + country 
       }); 
      } else { 
       alert('Geocode was not successful for the following reason: ' + status); 
      } 
     }); 
    } 

    //now add markers 
    @foreach (var item in Model.Events) { 
     @:placeMarkerForAddress('@item.Location.Address', '@item.Location.City', '@item.Location.PostCode', 'UK'); 
     @:console.log('boo!'); 
    } 

    // -------------------------------------------------- // 
    // -------------------------------------------------- // 
    // -------------------------------------------------- // 
    // -------------------------------------------------- // 


    // Check to see if this browser supports geolocation. 
    if (navigator.geolocation) { 

     // This is the location marker that we will be using 
     // on the map. Let's store a reference to it here so 
     // that it can be updated in several places. 
     var locationMarker = null; 


     // Get the location of the user's browser using the 
     // native geolocation service. When we invoke this method 
     // only the first callback is requied. The second 
     // callback - the error handler - and the third 
     // argument - our configuration options - are optional. 
     navigator.geolocation.getCurrentPosition(
      function (position) { 

       // Check to see if there is already a location. 
       // There is a bug in FireFox where this gets 
       // invoked more than once with a cahced result. 
       if (locationMarker) { 
        return; 
       } 

       // Log that this is the initial position. 
       console.log("Initial Position Found"); 

       // Add a marker to the map using the position. 
       locationMarker = addMarker(
        position.coords.latitude, 
        position.coords.longitude, 
        "Initial Position" 
       ); 
      }, 
      function (error) { 
       console.log("Something went wrong: ", error); 
      }, 
      { 
       timeout: (5 * 1000), 
       maximumAge: (1000 * 60 * 15), 
       enableHighAccuracy: true 
      } 
     ); 

     // Now tha twe have asked for the position of the user, 
     // let's watch the position to see if it updates. This 
     // can happen if the user physically moves, of if more 
     // accurate location information has been found (ex. 
     // GPS vs. IP address). 
     // 
     // NOTE: This acts much like the native setInterval(), 
     // invoking the given callback a number of times to 
     // monitor the position. As such, it returns a "timer ID" 
     // that can be used to later stop the monitoring. 
     var positionTimer = navigator.geolocation.watchPosition(
      function (position) { 

       // Log that a newer, perhaps more accurate 
       // position has been found. 
       console.log("Newer Position Found"); 

       // Set the new position of the existing marker. 
       updateMarker(
        locationMarker, 
        position.coords.latitude, 
        position.coords.longitude, 
        "Updated/Accurate Position" 
       ); 
      } 
     ); 

     // If the position hasn't updated within 5 minutes, stop 
     // monitoring the position for changes. 
     setTimeout(
      function() { 
       // Clear the position watcher. 
       navigator.geolocation.clearWatch(positionTimer); 
      }, 
      (1000 * 60 * 5) 
     ); 
    } 
</script> 

나는 혼란 스러워요! FireBug를 사용하여 JS 디버깅을 시도했지만 GeoCode API에 일종의 타임 아웃 메커니즘이 있어야한다고 생각합니다. 디버그 모드로 코드를 이동하려고하면 오류가 발생합니다. 또한 내지도가 사용자가 찾은 위치를 중심으로 정렬되지 않는 이유에 대해 머리 글자를 쓸 수 없습니다.

+1

를 이동하는 콜백을 정의하는 비동기 호출입니다. 나는 이것이 디버깅에 문제가있는 이유라고 생각합니다. 콜백 함수에 중단 점을 설정하십시오. 또한 현재 코드를 게시하십시오. – Khepri

+0

@Khepri 코드가 추가되었습니다. 감사합니다. – Ciwan

+0

geolocator 요청의 국가를 설정하거나 전체 주소를 사용하는 경우 (현재는 주소 만 전달하는 경우) 더 나은 검색 결과를 얻을 수 있습니다. 'geocoder.geocode ({'주소 ': 주소', '+ 도시 +', '+ 우편 번호 +', '+ 국가', '지역': '영국'}, 기능 .....' – kevmc

답변

1

function placeMarkerForAddress(address, city, postcode, country) { 
    var fullAddress = address + ', ' + city + ', ' + postcode + ', ' + country; 
    geocoder.geocode({ 'address': fullAddress, 'region':'UK'}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var marker = new google.maps.Marker({ 
       map: map, 
       position: results[0].geometry.location, 
       title: fullAddress 
      }); 
     } else { 
       alert('Geocode was not successful for the following reason: ' + status); 
     } 
    }); 
} 

그리고 때 당신의 geolocator 요청에 대한 전체 주소를 사용하고 (당신의 모든 주소가 영국에있는 경우), 이것은 조금에게 검색 범위를 좁힐해야 영국 지역을 설정하십시오 당신이지도의 중심에 필요한 업데이트 된 위치를 얻을뿐만 아니라 구글이 전화 위치 정보를 확인 마커를

function updateMarker(marker, latitude, longitude, label){ 
    // Update the position. 
    var pos=new google.maps.LatLng(latitude,longitude); 
    // move the marker 
    marker.setPosition(pos); 
    // centre the map 
    marker.getMap().setCenter(pos); 
    // Update the title if it was provided. 
    if (label){ 
     marker.setTitle(label); 
    } 
} 
+0

감사합니다. 많은 Kevmc. 마커는 이제 정확한 위치에 나타납니다. 그러나 센터링에 대해서는 파란색 마커 (사용자 위치)를 중심으로 한 맵만 원합니다. 여전히 작동하지 않습니다. ( – Ciwan

+0

그런 경우 제거해야합니다. updateMarker 함수의'marker.getMap() .setCenter (pos);'행과'console.log ("Newer Found Found"); locationMarker.getMap()과 같은 것을 geolocation.watchPosition 핸들러에 추가하십시오. setCenter (new google.maps.LatLng (position.coords.latitude, position.coords.longitude)) ' – kevmc

+0

그걸했습니다. 정말 고마워요. :) – Ciwan

관련 문제