Overlaying and syncing amCharts map with Google Maps API
This demo shows how we can create and overlay a MapChart over Google Maps using Maps JavaScript API, complete with total syncing of zoom and pan.
Open in:New tab
/** * --------------------------------------- * This demo was created using amCharts 5. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v5/ * --------------------------------------- */
/** * --------------------------------------- * Create the Google Map * --------------------------------------- */var gmap;
function initMap() { gmap = new google.maps.Map(document.getElementById("gmap"), { center: { lat: 0, lng: 0 }, zoom: 1, scrollwheel: true, disableDefaultUI: true });}
initMap();
/** * --------------------------------------- * Create the amCharts Map * --------------------------------------- */
// Create root and chartvar root = am5.Root.new("ammap");
// Set themesroot.setThemes([am5themes_Animated.new(root)]);
var chart = root.container.children.push( am5map.MapChart.new(root, { panX: "rotateX", projection: am5map.geoMercator(), animationDuration: 300 }));
// Create polygon seriesvar polygonSeries = chart.series.push( am5map.MapPolygonSeries.new(root, { geoJSON: am5geodata_worldLow, exclude: ["AQ"] }));
polygonSeries.mapPolygons.template.setAll({ tooltipText: "{name}", interactive: true, fillOpacity: 0.5});
polygonSeries.mapPolygons.template.states.create("hover", { fill: am5.color(0x677935)});
// Zoom controlchart.set("zoomControl", am5map.ZoomControl.new(root, {}));
// Sync with Google Maps stuffchart.on("zoomLevel", updateMapPosition);chart.on("rotationX", updateMapPosition);chart.on("rotationY", updateMapPosition);chart.on("translateX", updateMapPosition);chart.on("translateY", updateMapPosition);polygonSeries.on("datavalidated", updateMapPosition);
function updateMapPosition(ev) { if (typeof gmap === "undefined") return;
// set google map zoom level: gmap.setZoom(Math.log2(chart.get("zoomLevel")) + 1);
// sync position gmap.setCenter({ // a small adjustment needed for this div size: lat: chart.geoPoint().latitude, lng: chart.geoPoint().longitude });}<!-- Google includes -->
<!-- amCharts includes -->
<!-- HTML --><div id="maps"> <div id="gmap" class="mapdiv" style="visibility: visible"></div> <div id="ammap" class="mapdiv" style="visibility: visible"></div></div>body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";}
#maps { width: 510px; height: 500px; border: 0px solid #eee; margin: 0px auto; position: relative;}
.mapdiv { width: 510px; height: 500px; position: absolute; top: 0; left: 0;}map-overlaid-and-synced-with-google-map