单击更改 google 地图位置

Change google maps location onclick

我在网上找到了一个很棒的代码,我正尝试使用一个按钮将标记移动到另一个位置。我想我需要通过单击事件触发变量 "targetLocation",但我找不到具体方法。或者我应该创建像 targetlocation2 和 marker2 这样的变量吗?

位置 1: 41.118555", 28.2743889

位置 2:38.9152733,-111.6676686

html:

<a href="#location1">Address 1</a>
<a href="#location2">Address 2</a>

代码:

if ($("#map .google-maps").length) {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var targetLocation = new google.maps.LatLng("41.118555", "28.2743889");

var myOptions = {
    center: targetLocation,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    zoom: 13,
    scrollwheel: false,
    streetViewControl: false,
    mapTypeControl: false,
    disableDoubleClickZoom: true,
    styles: [
    {
        featureType: "all",
        stylers: [
        {saturation: -100}
        ]
    }
    ]
}

var map = new google.maps.Map($("#map .google-maps")[0], myOptions);
directionsDisplay.setMap(map);

var marker = new google.maps.Marker({
    position: targetLocation,
    map: map,
    icon: "marker.png",
    visible: true
});

}

在事件处理程序中使用 setPosition

$(selector).on('click', function(){
     newLocation = new google.maps.LatLng(0,0);
     marker.setPosition( newLocation );
});