Search code examples
javascriptamchartsammap

How to highlight selected location on amCharts


I am using amCharts. On hover of the location and on click of the particular location I am able to highlight the area.

rollOverOutlineColor: "#000000",
rollOverColor: "#62B4EB",
selectedColor: "#0078c8",

But clicking on the next location, current one will highlight and the old one will loose. I want to show all selected /clicked location to be highlighted on a particular color.

map = new AmCharts.AmMap();
map.areasSettings = {
    autoZoom: false,
    rollOverOutlineColor: "#000000",
    rollOverColor: "#62B4EB",
    selectedColor: "#0078c8",
    color: "#999999",
    selectable:true
};

map.pathToImages = '/images/';

map.dataProvider = data;

enter image description here

Please suggest.


Solution

  • Your solution comes in the form of using area's showAsSelected property.

    When click event (clickMapObject) occurs, you can set showAsSelected property of clicked area to keep it selected.

    map.addListener("clickMapObject", function(event) {
      event.mapObject.showAsSelected = true;
    });
    

    Please note that showAsSelected was introduced in some later 3.x version. (I'm sorry I can't quite recall which one) If you are using old version of JavaScript Maps, it might not work.

    Here's a working demo with the current version:

    var map;
    var data = {
      "map": "worldLow",
      "getAreasFromMap": true
    };
    
    map = new AmCharts.AmMap();
    map.areasSettings = {
      autoZoom: false,
      rollOverOutlineColor: "#000000",
      rollOverColor: "#62B4EB",
      selectedColor: "#0078c8",
      color: "#999999",
      selectable: true
    };
    
    map.pathToImages = '/images/';
    
    map.dataProvider = data;
    
    map.addListener("clickMapObject", function(event) {
      event.mapObject.showAsSelected = true;
    });
    
    map.write("chartdiv");
    <script src="http://www.amcharts.com/lib/3/ammap.js"></script>
    <script src="http://www.amcharts.com/lib/3/maps/js/worldLow.js"></script>
    <div id="chartdiv" style="width: 100%; height: 400px;"></div>


    UPDATE: In case you want to toggle whole groups of countries using their groupId parameter, here's how this could be done:

    map.addListener("clickMapObject", function(event) {
      if (event.mapObject.groupId !== undefined) {
        for(var i = 0; i < map.dataProvider.areas.length; i++) {
          var area = map.dataProvider.areas[i];
          if (area.groupId == event.mapObject.groupId) {
            area.showAsSelected = true;
          }
        }
        map.validateData();
      }
      else {
        event.mapObject.showAsSelected = true;
      }
    });