2015-05-02 10 views
0

хорошо здесь то, что я есть. Я использую Smarty для заполнения координат, вытащил из MySQL, Мое маленькое приложение привлекает более 300 полигонов на карту Великобритании за пределы графства. Мне удалось сделать это просто прекрасно, а также покрасить их, как я хочу. Теперь у меня есть проблема, я не могу получить информационные поля для показа.Google Maps API v3 не может получить информацию коробки, чтобы показать на динамически создаваемые многоугольники

Чуть подробнее, Причина в том, что counties_zone некоторая области есть острова, которые разбивают многоугольник делает беспорядок. поэтому мне пришлось их зонировать, чтобы правильно закрыть полигоны.

остальная часть моих умных переменных должна быть довольно понятной.

<script> 
var map; 
var infoWindow; 

function initialize() { 
    var mapOptions={ 
     zoom: 6, 
     center: new google.maps.LatLng(54.049976288319, - 2.8110410026615), 
     mapTypeId: google.maps.MapTypeId.TERRAIN 
    }; 

    var map=new google.maps.Map(document.getElementById('googleMap'), 
      mapOptions); 

    var counties={ 
    }; 
{foreach $counties as $county => $area} 
    {foreach $area as $zone => $coords} 
    counties["{$county}_{$zone}"]=new google.maps.Polygon({ 
     paths: [ 
     {foreach $coords as $coord} 
       new google.maps.LatLng({$coord.0}, {$coord.1}), 
     {/foreach} 
     ], 
     strokeColor: "#0000ff", 
     strokeOpacity: 0.8, 
     strokeWeight: 2, 
     fillColor: "#{$coord.2}", 
     fillOpacity: 0.6 
    }); 
    counties["{$county}_{$zone}"].setMap(map); 

    infowindow = new google.maps.InfoWindow(); 
    google.maps.event.addListener(counties["{$county}_{$zone}"], 'click', showInfoCounty); 

    {/foreach} 
{/foreach} 

} 

function showInfoCounty(event) { 
    var contentString="<b>County</b><br />"; 
    contentString+="County name"; 

    // thhis works. 
    console.log(contentString); 

    // this works 
    this.setOptions({ fillColor: "#000000" }); 

    // this doesnt work. 

    // Replace our Info Window's content and position 
    infowindow.setContent(contentString); 
    infowindow.setPosition(event.latLng); 
    infowindow.open(map); 
} 


google.maps.event.addDomListener(window, 'load', initialize); 
</script> 

ответ

1

Переменная map не определена в showInfoCounty рутина. Сделайте его глобальным (он в настоящее время локален для функции инициализации или, по крайней мере, версия, которую вы инициализируете, есть глобальная, но она не инициализируется).

Minimal, Complete, испытана и читаемый пример, показывающий вопрос: fiddle

Изменение:

var map=new google.maps.Map(document.getElementById('googleMap'), 
     mapOptions); 

To:

map=new google.maps.Map(document.getElementById('googleMap'), 
     mapOptions); 

working fiddle

+0

Спасибо большое, я честно не думал, что все будет так просто! мне просто нужно расположить его сейчас, но это удовольствие от этого, я застрял в кругах! – Chris

0

Хорошо, так вот мое окончательное решение , Я взял на борт вашу записку о масштабах и не будут удалены дополнительные функции, так что глобальный охват больше не является проблемой.

/** 
This code snippet accepts an array as follows for each polygon. 
Colour should really be moved up a county level. 

county_1 [0] 

     Zone [0] 

      Points [0] [ lat, lng, colour ] (colour code without the prepended # 
      Points [1] [ lat, lng, colour ] 
      Points [2] [ lat, lng, colour ] 

county_1 [0] 

     Zone [0] 

      Point [0] [ lat, lng, colour ] 
      Point [1] [ lat, lng, colour ] 
      Point [2] [ lat, lng, colour ] 
etc... 
etc... 

**/ 

// Removed global vars. 
function initialize() { 
    var mapOptions={ 
     zoom: 6, 
     center: { lat:54.049976288319, lng:-2.8110410026615 }, 
     mapTypeId: google.maps.MapTypeId.TERRAIN 
    }; 

    // brought map back into local scope. 
    var map=new google.maps.Map(document.getElementById('googleMap'), 
      mapOptions); 

    // Initialise counties for populating the polygons. 
    var counties={ 
    }; 

// I use smarty so thats why the odd looking loop, 
// you will likely need to modify this and the 
// associated ($vars} to your own needs. 
{foreach $counties as $county => $area} 
    {foreach $area as $zone => $coords} 
    counties["{$county}_{$zone}"]=new google.maps.Polygon({ 
     paths: [ 
     {foreach $coords as $coord} 
       new google.maps.LatLng({$coord.0}, {$coord.1}), 
     {/foreach} 
     ], 
     strokeColor: "#0000ff", 
     strokeOpacity: 0.8, 
     strokeWeight: 2, 
     fillColor: "#{$coord.2}", 
     fillOpacity: 0.6 
    }); 

    // polygon assign to map 
    counties["{$county}_{$zone}"].setMap(map); 

    // set your info window information to collect later. 
    counties["{$county}_{$zone}"].set("Info", '{$county}');  

    // add a listner for the click. 
    google.maps.event.addListener(counties["{$county}_{$zone}"], 'click', function(event) { 

     // create the new info window. 
     var infoWindow = new google.maps.InfoWindow(); 

     // get the previously set data and set it into the new info window. 
     infoWindow.setContent(counties["{$county}_{$zone}"].get("Info")); 

     // open the info window. 
     infoWindow.open(map); 

     // position the window, open at the click position with event.latLng 
     infoWindow.setPosition(event.latLng); 
    }); 

    {/foreach} 
{/foreach} 

} 

// generate the map. 
google.maps.event.addDomListener(window, 'load', initialize); 

Это результат. Visual of the script output.

 Смежные вопросы

  • Нет связанных вопросов^_^