0

我有位置存储在数据库中,我正在循环浏览它们并在Google Maps(API v3)上为每个位置(JS和Razor的混合)放下标记。谷歌地图地理代码显示错误的地址

几天前我在StackOverFlow上使用的代码是a question I asked。有问题的两个地址是:

  1. 6-7厅举行,斯伯丁,PE11,撒上,英国
  2. 29联盟街,伯明翰,B2 4LR,英国

这些地址显示完美on here 。但是当我在我的网站(当地本地主机)上尝试它们时,会在旧金山和美国路易斯安那州出现!

这里是我使用的JavaScript代码(注意,一些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

Google geolocate调用是定义回调的异步调用。我猜这就是为什么你在调试时遇到麻烦。在回调函数中设置断点。另外,请发布您的当前代码。 – Khepri

+0

@Khepri代码已添加,谢谢 – Ciwan

+0

如果您设置了国家/地区的地理定位器请求,或者使用完整地址(目前您只传递街道地址),则可能会获得更好的搜索结果。像geocoder.geocode({'地址':地址','+城市+','+邮编+','+国家,'地区':'英国'},功能.....' – kevmc

回答

1

尝试使用完整的地址为您geolocator请求,该区域设置为英国(如果您所有的地址都在英国),这应该缩小搜索了一下

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); 
     } 
    }); 
} 

当你获取更新的位置,您需要将地图居中以及移动标记

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);'行并添加一个到geolocation.watchPosition处理程序中,如'console.log(“Newer Position Found”); locationMarker.getMap()。 setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude))' – kevmc

+0

这样做了,非常感谢你:) – Ciwan