Google Maps with counties overlay?

I have no experience working with Google Maps, but I'd like to embed a "Choose your county" map in my webapp. My app only targets California, so it only needs to support one state, but I can't find any easy way to do this (without manually drawing overlay polygons for all the county lines).

I assumed I'd easily be able to find examples of "Choose your county"-style interfaces on Google somehow, but the only thing I found was this -- http://maps.huge.info/county.htm -- and I'm leaning towards hitting their API to pull the geometry for the whole state if I can't find a better option.

Does anyone have any experience or insight to help make this a little easier?

18
задан Cœur 8 February 2018 в 20:39
поделиться

1 ответ

API Карт Google не предоставляет полигонов округов или каких-либо других предопределенных границ штатов или стран. Поэтому основной проблемой здесь является получение данных полигона.

Многоугольник в Google Maps API определяется путем создания массива из LatLng объектов (при условии, что вы используете v3 API):

var bermudaTriangleCoords = [
  new google.maps.LatLng(25.774252, -80.190262),
  new google.maps.LatLng(18.466465, -66.118292),
  new google.maps.LatLng(32.321384, -64.757370),
  new google.maps.LatLng(25.774252, -80.190262)
];    

Затем вы могли бы использовать этот массив для создания ] Объект Polygon :

var bermudaTriangle = new google.maps.Polygon({
  paths: bermudaTriangleCoords,
  strokeColor: '#FF0000',
  strokeOpacity: 0.8,
  strokeWeight: 2,
  fillColor: '#FF0000',
  fillOpacity: 0.35
});

И, наконец, покажите его на карте, вызвав метод setMap () :

bermudaTriangle.setMap(map);    // Assuming map is your google.maps.Map object

Если вы сохраните ссылку на свой объект Polygon , вы также можете скрыть его, передав null методу setMap () :

bermudaTriangle.setMap(null); 

Поэтому вы можете подумать о создании объекта JavaScript с именем свойства для каждого округа. Это позволит вам получать полигональные объекты из названия округов в O (1) (постоянное время), без необходимости перебирать всю коллекцию. Рассмотрим следующий пример:

// Let's start with an empty object:
var counties = {    
};

// Now let's add a county polygon:
counties['Alameda'] = new google.maps.Polygon({
  paths: [
    // This is not real data:
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.757370),
    new google.maps.LatLng(25.774252, -80.190262)
    // ...
  ],
  strokeColor: '#FF0000',
  strokeOpacity: 0.8,
  strokeWeight: 2,
  fillColor: '#FF0000',
  fillOpacity: 0.3
});

// Next county:
counties['Alpine'] = new google.maps.Polygon({
  // Same stuff
});

// And so on...

Объект округов будет нашим хранилищем данных. Когда пользователь ищет "Эльдорадо", вы можете просто показать многоугольник следующим образом:

counties['El Dorado'].setMap(map);

Если вы сохраняете ссылку на округ, который ранее искали, вы также можете вызвать setMap (null) , чтобы скрыть предыдущий polygon:

var userInput = 'El Dorado';
var latestSearch = null;

// Check if the county exists in our data store:
if (counties.hasOwnProperty(userInput)) {
  // It does - So hide the previous polygon if there was one:
  if (latestSearch) {
    latestSearch.setMap(null);
  }
  // Show the polygon for the searched county:
  latestSearch = counties[userInput].setMap(map);
}
else {
  alert('Error: The ' + userInput + ' county was not found');
}

Надеюсь, вы двинетесь в правильном направлении.

34
ответ дан 30 November 2019 в 06:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: