Mitch S
Mitch S

Reputation: 13

Create Google Map of the US, no markers, but each state would be its own marker (boundary)

I'm new to Google Maps.

I'm searching for a way to use Google Maps to do the following:

  1. Create a map of the United States, showing only boundaries of the states
  2. No pin points / markers
  3. The states would have a ‘mouse over’ effect to display content (desktop)
  4. The states would have an ‘on click’ event to display content (mobile)

EXAMPLE: http://maps.debt.com/ccus-geo-map.html (but without the pin points / markers and this map is not responsive)

Have any of you seen anything like this using Google Maps and if so, where? Is there a tutorial to perform this? The google docs were not helpful as markers were displayed and this is not the desired result.

Thanks,

Mitch

An example of the code I created below using the Google Documents, but this was not providing the desired results either ...

    function initialize() {

    var locations = [
    ['California (LOS ANGELES)', 34.0522, -118.2437, 1],
    ['Florida (MIAMI)', 25.7617, -80.1918, 2],
    ['Maine (HOULTON)', 46.1262, -67.8402, 3],
    ['Washington (CLALLAM)', 48.253517, -124.257798, 4]
    ];
    var mapProp = {
        center: new google.maps.LatLng(39.8282, -98.5795), /* exact center of the US */
        zoom: 4,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        /*
            ROADMAP (normal, default 2D map)
            SATELLITE (photographic map)
            HYBRID (photographic map + roads and city names)
            TERRAIN (map with mountains, rivers, etc.)
        */
    };
    var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
    var marker, i;
    var markers = new Array();
    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });
        markers.push(marker);
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
}
google.maps.event.addDomListener(window, 'load', initialize)

Upvotes: 0

Views: 1980

Answers (1)

Matej P.
Matej P.

Reputation: 5383

You have to load boundaries over your maps. The boundaries can be in KML format, geoJSON format, etc and depending on that you can use google maps KML Layer or Data Layer or even simple google.maps.Polygons.

I have created an example for this using Data Layer, take a look at this answer on SO (In answer, run the javascript snippet and choose "LOAD US STATES BOUNDARIES" from the dropdown above the map), it solves very similar problem to yours.

The boundary files are publicly available from US CENSUS (not sure about commercial licensing though, you will have to check that yourself) as shapefiles. More on how to convert shapefile to desired format, read the referenced answer.

EDIT

For the sake of being complete, here is working example with only US states boundaries and both hover and click listeners:

var map = null;
var my_boundaries = {};
var data_layer;
var info_window;

//initialize map on document ready
$(document).ready(function(){
	var latlng = new google.maps.LatLng(20.723080, -73.984340); //you can use any location as center on map startup
	var myOptions = {
		zoom: 2,
		center: latlng,
		mapTypeControl: true,
		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		navigationControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	google.maps.event.addListener(map, 'click', function(){
		if(info_window){
			info_window.setMap(null);
			info_window = null;
		}
	});
	loadBoundariesFromGeoJson("https://raw.githubusercontent.com/matej-pavla/Google-Mapshttps://raw.githubusercontent.com/matej-pavla/Google-Maps-Examples/master/BoundariesExample/geojsons/us.states.geo.json");
});

function initializeDataLayer(){
	if(data_layer){
		data_layer.forEach(function(feature) {
			data_layer.remove(feature);
		});
		data_layer = null;
	}
	data_layer = new google.maps.Data({map: map}); //initialize data layer which contains the boundaries. It's possible to have multiple data layers on one map
	data_layer.setStyle({ //using set style we can set styles for all boundaries at once
		fillColor: 'white',
		strokeWeight: 1,
		fillOpacity: 0.1
	});

	data_layer.addListener('click', function(e) { //we can listen for a boundary click and identify boundary based on e.feature.getProperty('boundary_id'); we set when adding boundary to data layer
		var boundary_id = e.feature.getProperty('boundary_id');
		var boundary_name = "NOT SET";
		if(boundary_id && my_boundaries[boundary_id] && my_boundaries[boundary_id].name) boundary_name = my_boundaries[boundary_id].name;
		if(info_window){
			info_window.setMap(null);
			info_window = null;
		}
		info_window = new google.maps.InfoWindow({
			content: '<div>You have clicked a boundary: <span style="color:red;">' + boundary_name + '</span></div>',
			size: new google.maps.Size(150,50),
			position: e.latLng, map: map
		});
	});

	data_layer.addListener('mouseover', function(e) {
		data_layer.overrideStyle(e.feature, {
			strokeWeight: 3,
			strokeColor: '#ff0000'
		});
		var boundary_id = e.feature.getProperty('boundary_id');
		var boundary_name = "NOT SET";
		if(boundary_id && my_boundaries[boundary_id] && my_boundaries[boundary_id].name) boundary_name = my_boundaries[boundary_id].name;
		$('#bname').html(boundary_name);
	});

	data_layer.addListener('mouseout', function(e) {
		data_layer.overrideStyle(e.feature, {
			strokeWeight: 1,
			strokeColor: ''
		});
		$('#bname').html("");
	});
}

function loadBoundariesFromGeoJson(geo_json_url) {
	initializeDataLayer();
	$.getJSON(geo_json_url, function (data) {
		if (data.type == "FeatureCollection") { //we have a collection of boundaries in geojson format
			if (data.features) {
				for (var i = 0; i < data.features.length; i++) {
					var boundary_id = i + 1;
					var new_boundary = {};
					if (!data.features[i].properties) data.features[i].properties = {};
					data.features[i].properties.boundary_id = boundary_id; //we will use this id to identify boundary later when clicking on it
					data_layer.addGeoJson(data.features[i], {idPropertyName: 'boundary_id'});
					new_boundary.feature = data_layer.getFeatureById(boundary_id);
					if (data.features[i].properties.name) new_boundary.name = data.features[i].properties.name;
					if (data.features[i].properties.NAME) new_boundary.name = data.features[i].properties.NAME;
					my_boundaries[boundary_id] = new_boundary;
				}
			}
		}
	});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("maps", "3",{other_params:"sensor=false"});
</script>
<body style="margin:0px; padding:0px;" >
     <div style="float:left;clear:both;height:15px;">
       You are hovering over: <span id="bname" style="font-weight:bold"></span></div>
	<div id="map_canvas" style="height:400px; width:500px;"></div>
</body>

Upvotes: 2

Related Questions