简体   繁体   English

更改Jquery单击上的Google Map标记

[英]Change Google Map marker on Jquery click

I'm trying to change GoogleMap marker icon by clicking div and using jquery. 我正在尝试通过单击div并使用jquery来更改GoogleMap标记图标。 But it doesn't seem to be working, marker icon doesn't change. 但这似乎不起作用,标记图标没有改变。 I assigned a variable that contains image path, but the thing is that if jquery changes it, it stays inside jquery function and is not passed back to global value. 我分配了一个包含图像路径的变量,但事实是,如果jquery更改了它,它将保留在jquery函数内部,并且不会传递回全局值。 Here is my code: 这是我的代码:

JS part JS部分

$(document).ready(function() {

$('#hurricanes').click(function (e){
iconic=jQuery(this).attr('hurr.png');
    initMap();
});
$('#earthquakes').click(function (e){
iconic=jQuery(this).attr('durr.png');
    initMap();
});    
});


var iconBase = 'img/';
var iconic;
function createMarker(latlng, name, address1, address2, postalCode) {
    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        title: name,
        icon: iconBase + iconic
    });

}

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: -0.397,
            lng: 10.644
        },
        zoom: 2,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        disableDefaultUI: true
    });
    displayMarkers();
}

And HTML buttons: 和HTML按钮:

    <div id="hurricanes" class="choices">HURRICANES</div>
    <div id="earthquakes" class="choices">EARTHQUAKES</div>

you should reinitialize the map using JavaScript after you changed the marker. 您应该在更改标记后使用JavaScript重新初始化地图。 Have a look in the API Reference for all the options: https://developers.google.com/maps/documentation/javascript/3.exp/reference 查看API参考中的所有选项: https : //developers.google.com/maps/documentation/javascript/3.exp/reference

Although I am not quite sure what you are exactly going to do, you can also remove the markers in specific coordinates and then add the new ones with new marker icons. 尽管我不确定您要做什么,但是您也可以删除特定坐标中的标记,然后使用新的标记图标添加新的标记。

I found the solution by reinitializing both functions: 我通过重新初始化两个函数找到了解决方案:

$(document).ready(function() {

$('#hurricanes').click(function (e){
iconic='hurr.png';
    createMarker();
    initMap();
    console.log(iconic);
});
$('#earthquakes').click(function (e){
iconic='durr.png';
    createMarker();
    initMap();
    console.log(iconic);
});


});

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

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