2amigos / yii2-leaflet-extension

Yii 2 Extension library to display interactive maps with Leaflet .
http://yiiwheels.com
Other
30 stars 26 forks source link

Map as global variable #5

Closed fabioaccetta closed 10 years ago

fabioaccetta commented 10 years ago

Looking inside generated js code, I see that the "map" variable is local, inside a map_init() function, so I can't use it outside its scope.

Is there a plan to make this variable global, so can be used page-wide? Or must the developer implement something like this?

Inside a view:

$this->registerJS('var globalMap;', View::POS_HEAD); // global variable

$tileConfig = [
    '...' => '...',
    'map' => 'localMap', // local variable
];
$tileLayer = new TileLayer($tileConfig);

$leafConfig = [
    '...' => '...',
    'tileLayer' => $tileLayer,
];
$leafLet = new LeafLet($leafConfig);
$leafLet->appendJS('globalMap = localMap;'); // use globalMap page-wide

Thanks. Regards.

tonydspaniard commented 10 years ago

You have done it exactly as I do... there is no need to added to the POS_HEAD but is perfect.

I thought is better to leave the developer to do it as you explained. A good concept to do a wiki.

gfargo commented 9 years ago

:+1: great post, very helpful.

edit: @nigelterry provided a better, safer solution below. now to refactor 😝

nigelterry commented 8 years ago

As a variant, use appendJs() to insert whatever js you need within the scope that includes map.

For example to insert a block of js from a file, try: $leaflet->appendJs(file_get_contents('js/maptools.js'));

This saves making a global which is rarely a good idea.