简体   繁体   English

谷歌地图设置新的标记位置和panTo

[英]google map set new marker position and panTo

I am trying to modify an existing theme's js to be able to show different locations on the map. 我正在尝试修改现有主题的js,以便能够在地图上显示不同的位置。 here is the original code: 这是原始代码:

function initialize() {
    var map;
    var brooklyn = new google.maps.LatLng(parseFloat("<?php echo $coordinates[0]; ?>"), parseFloat("<?php echo $coordinates[1]; ?>"));
    var stylez = [{
        featureType: "all",
        elementType: "all",
        stylers: [{
                saturation: -100
            } // <-- THIS
        ]
    }];

    var mapOptions = {
        zoom: parseInt("<?php the_field("google_map_zoom_level"); ?>"),
        center: brooklyn,
        mapTypeControlOptions: {
            mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'tehgrayz']
        }
    };

    map = new google.maps.Map(document.getElementById("map"), mapOptions);

    var mapType = new google.maps.StyledMapType(stylez, {
        name: "Grayscale"
    });
    map.mapTypes.set('tehgrayz', mapType);
    map.setMapTypeId('tehgrayz');
    marker = new google.maps.Marker({
        title: "<?php echo $map["
        address "]; ?>",
        position: new google.maps.LatLng(parseFloat("<?php echo $coordinates[0]; ?>"), parseFloat("<?php echo $coordinates[1]; ?>")),
        map: map
    });
}
initialize();
 //google.maps.event.addDomListener(window, 'load', initialize);
}

I have also managed to use various tutorials to create a function that moves the marker to a new location. 我还设法使用各种教程来创建一个将标记移动到新位置的函数。

function changeMarkerPos(lat, lon){
    myLatLng = new google.maps.LatLng(lat, lon);
    marker.setPosition(myLatLng);
    map.panTo(myLatLng);
}

However, although the marker does move, the map does not center to is, as I would like. 然而,尽管标记确实在移动,但地图并不像我想的那样居中。 Can anyone help me out? 谁能帮我吗? I am not that good with js, so please keep things simple... 我对js不太好,所以请保持简单......

Thanks!!! 谢谢!!!

You need to declare the map variable globally. 您需要全局声明map变量。 The function changeMarkerPos cannot currently use it. 函数changeMarkerPos目前无法使用它。

var map;
function initialize() {
    var brooklyn = new googl............

EDIT - The following will not make any difference this time. 编辑 - 这次没有任何区别。 setCenter() is useful but not the answer to your question. setCenter()很有用,但不是你问题的答案。

I was doing something similar earlier this week and used map.setCenter(); 本周早些时候我做了类似的事情并使用了map.setCenter(); What about this: 那这个呢:

function changeMarkerPos(lat, lon){
    myLatLng = new google.maps.LatLng(lat, lon);
    marker.setPosition(myLatLng);
    map.panTo(myLatLng); 
    map.setCenter(myLatLng);    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM