【问题标题】:Markers will not show up from url json data标记不会从 url json 数据中显示
【发布时间】:2014-01-22 11:10:03
【问题描述】:

我有一张地图,可以从名为 Police.uk 的 API 中获取数据。它通过在地图上拖放一个点来获取数据,并显示半径 1 英里内的区域的犯罪情况。现在我正在尝试从用户那里获取一个邮政编码(地理编码)并加载该区域的数据。如果没有地理编码字段,我不会收到任何错误,但使用地理编码服务,它无法加载 url 资源。 这是我的代码。问题出在函数 geocodeCrimeLocation 中。如果有点长,我很抱歉。我只是想清楚我正在实施什么。

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <!-- jQuery CDN -->
<script>
    var geocoder;
    var map;
    var latlng;
    var markers = [];
    var myPositionMarker = null;;
      //Initializing the map
      function initialize() {
        var lat = 52.629729;
        var lng = -1.131592;
        geocoder = new google.maps.Geocoder();
        latlng = new google.maps.LatLng(lat, lng);
        var mapOptions = {
            zoom: 8,
            center: latlng
        }
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        getCrimeByLocation(lat, lng);
      }

        function fitBoundsMap(){
            //Zoom and center the map to fit the markers  
            //This logic could be conbined with the marker creation.  
            //Just keeping it separate for code clarity.  
            var bounds = new google.maps.LatLngBounds();  
            for (index in markers) {  
                var data = markers[index];
                bounds.extend(data.position);  
            }  
            map.fitBounds(bounds);
        }
        function addMyPositionMarker(lat, lng) {
            if(myPositionMarker != null){
                myPositionMarker.setMap(null); // clearing prev req position
            }

            myPositionMarker = new google.maps.Marker({
                position: new google.maps.LatLng(lat, lng),
                map: map,
                draggable: true,
                zIndex: 99999,
                icon: 'http://i.stack.imgur.com/orZ4x.png'
            });

            google.maps.event.addListener(myPositionMarker,'dragend',function(event) {
                getCrimeByLocation(event.latLng.lat(), event.latLng.lng());
            });
        }
        //Calling the JSON data from the website
        function getCrimeByLocation(lat, lng, date){
            if(date == null){
                var d = new Date();
                date = d.getFullYear() + '-' + (d.getMonth()+1);
                //hardcoding as of now as jan 2014 data is not there, remove when req
                date = "2013-01";
            }
            $.getJSON( "http://data.police.uk/api/crimes-street/all-crime?lat="+lat+"&lng="+lng+"&date="+date, function( data ) {
            while(markers.length > 0){
                markers.pop().setMap(null);
            }

            //marking the requested position
            addMyPositionMarker(lat, lng);

            $.each( data, function( key, val ) {
            //var myLatlng = new google.maps.LatLng(val.location.latitude, val.location.longitude);
                var marker = new google.maps.Marker({
                position: new google.maps.LatLng(val.location.latitude, val.location.longitude),
                map: map,
                animation: google.maps.Animation.DROP,
                draggable: false,
                title: val.location.street.name
                });
                markers.push(marker); // saving markers for reference, so that we can remove them later;
            });

            if(markers.length > 0){
                fitBoundsMap();
            }
            });
        }

function geocodeCrimeLocation(date){
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
         map.setCenter(results[0].geometry.location);
         var latitude = json.results[0].geometry.location.lat;
         var longitude = json.results[0].geometry.location.lng;

         if(date == null){
            var d = new Date();
            date = d.getFullYear() + '-' + (d.getMonth()+1);
            date = "2013-01";
         }
    $.getJSON( "http://data.police.uk/api/crimes-street/all-crime?   lat="+latitude+"&lng="+longitude+"&date="+date, function(data) {
    while(markers.length > 0){
          markers.pop().setMap(null);
    }

//marking the requested position
addMyPositionMarker(latitude, longitude);

$.each( data, function( key, val ) {
    //var myLatlng = new google.maps.LatLng(val.location.latitude, val.location.longitude);
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(val.location.latitude, val.location.longitude),
        map: map,
        animation: google.maps.Animation.DROP,
        draggable: false,
        title: val.location.street.name
    });
    markers.push(marker); // saving markers for reference, so that we can remove them later;
    });

if(markers.length > 0){
    fitBoundsMap();
}
});

} else {
     alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>

HTML:

<body onload="initialize()">
<!-- <div id="map-canvas" style="width: 320px; height: 480px;"></div> -->
<div id="map-canvas" style="width: 100%; height: 480px;"></div>
<div>
    <input id="address" type="textbox" placeholder = "Enter address, or postcode">
    <input type="button" value="Encode" onclick="geocodeCrimeLocation()">
</div>
</body>

如果有人能提出解决错误的建议,将不胜感激。谢谢

【问题讨论】:

  • 您用于纬度和经度的值是否可能被视为字符串,因为它们来自 JSON?将它们传递给 new google.maps.LatLng() 时,您可能想尝试将它们包装在 parseFloat(...)
  • 感谢您的回复。所以你的意思是var latitude = new google.maps.LatLng(parseFloat(results[0].geometry.location.lat));
  • 不像position: new google.maps.LatLng(parseFloat(val.location.latitude), parseFloat(val.location.longitude)),
  • 刚刚试过了,还是不行。不知道问题出在哪里。我添加了我的完整代码,如果你能提供答案,我一定会接受。

标签: javascript jquery json google-maps google-maps-api-3


【解决方案1】:

您应该会在

上看到明显的 javascript 错误
     var latitude = json.results[0].geometry.location.lat;
     var longitude = json.results[0].geometry.location.lng;

应该是:

     map.setCenter(results[0].geometry.location);
     var latitude = results[0].geometry.location.lat();
     var longitude = results[0].geometry.location.lng();

results[0].geometry.location 是google.maps.LatLng object

【讨论】:

  • 只是因为您的观察才开始工作。非常感谢。接受的答案。
【解决方案2】:

在这些代码行中(从地理编码器获取位置):

var latitude = json.results[0].geometry.location.lat;
var longitude = json.results[0].geometry.location.lng;

你需要json吗? ?我不明白你为什么会这样做,除非我很密集,因为对象结果被传递到函数中并且你将中心设置在我认为正在工作的那个对象之外?

【讨论】:

  • 是的,当我将它设置到中心时它可以工作。虽然没有 json 仍然无法工作,但我仍然收到错误消息。出于某种原因,它会将其视为错误请求。
  • 您在尝试调用犯罪统计网络服务时遇到错误?您是否提醒过长/纬度以查看是否存在格式问题?
  • 尝试使用var latitude = new google.maps.LatLng(parseFloat(results[0].geometry.location.lat)); 更改格式。警报也不显示。
  • 你知道网络服务使用的是什么投影吗? Google 使用 Sperical Mercator,如果存在不匹配可能会导致问题?
  • Web 服务是响应式的,我会获取数据,直到我对地址进行地理编码。所以这是我的 geocodeCrimeLocation(date) 函数里面的东西。
猜你喜欢
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 2014-01-25
相关资源
最近更新 更多