Google Maps API Geocoder获得正确的经度和纬度,但放置了错误的标记

时间:2018-12-29 20:02:29

标签: javascript api google-maps

下面是我的代码,使用我想要的地址并将其使用Google Maps API放置在地图上。每当我运行该页面时,即使我通过控制台记录从地址获得的经纬度,它也是将标记放置在加纳以南海洋上的中心位置,这是北爱尔兰贝尔法斯特的正确坐标。

google.maps.event.addDomListener(window, 'load', init);

function init() {

    var latNo = null;
    var lngNo = null;

    var postcode = $(".postcode-var").text();
    var address = "Belfast, Northern Ireland";

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            latNo = results[0].geometry.location.lat();
            lngNo = results[0].geometry.location.lng();
            console.log(latNo + "" + lngNo);
        } else {
            console.log("Cannot find address");
        }

    });

    var mapOptions = {
        zoom: 14,
        disableDefaultUI: true,
        center: new google.maps.LatLng(latNo, lngNo),
        styles: [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#6863CE"},{"visibility":"on"}]}]
    };

    var mapElement = document.getElementById('map');

    var map = new google.maps.Map(mapElement, mapOptions);

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(latNo, lngNo),
        map: map
    });

    }

1 个答案:

答案 0 :(得分:1)

请尝试不要在分配latNo和lngNo的地方重新声明var

val obs = arrayOf (arrayOf(5, 5),arrayOf(4, 2),arrayOf(2, 3))
println(obs.contains(arrayOf(2, 3))) // false

val obs1 = arrayListOf (arrayListOf(5, 5), arrayListOf(4, 2), arrayListOf(2, 3))
println(obs1.contains(arrayListOf(2, 3))) // true

为latNo和lngN声明var,将内容隐藏在if内容中

或尝试将坐标分配给现有标记

geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
        latNo = results[0].geometry.location.lat();
        lngNo = results[0].geometry.location.lng();
        console.log(latNo + "" + lngNo);
    } else {
        console.log("Cannot find address");
    }

});