最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically modify Google Maps Icons with SVG files - Stack Overflow

programmeradmin0浏览0评论

What I have:

I set the icon for a Google Maps v3 Marker with

var icon= {
    url: 'path/to/iconfile.svg',
    [...]
};

var marker = new google.maps.Marker({
    icon: icon
    [...]
});

And it displays fine.


What I want:

Is there a way I can get that svg file from marker, change some attributes, and set it back to the marker?

I know you can do marker.getIcon() to get the actual Icon object, but is there something similar to marker.getIcon().getElementByID("iconID").setAttribute("fill", #000000); (which doesn't work, obviously), where I can change the SVG file through javascript?

What I have:

I set the icon for a Google Maps v3 Marker with

var icon= {
    url: 'path/to/iconfile.svg',
    [...]
};

var marker = new google.maps.Marker({
    icon: icon
    [...]
});

And it displays fine.


What I want:

Is there a way I can get that svg file from marker, change some attributes, and set it back to the marker?

I know you can do marker.getIcon() to get the actual Icon object, but is there something similar to marker.getIcon().getElementByID("iconID").setAttribute("fill", #000000); (which doesn't work, obviously), where I can change the SVG file through javascript?

Share Improve this question asked Sep 26, 2014 at 21:43 ThePersonWithoutCThePersonWithoutC 1903 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

There is also a solution without the need to use URL.createObjectURL() which might be troublesome or not available in some cases.

You can use an alternative 'URL' with base64 encoded svg:

var svg = '<svg width="400" height="110"><rect width="300" height="100" /></svg>';
icon.url = 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg);

JavaScript (Firefox) btoa() is used to get the base64 encoding from the SVG text. Your may also use http://dopiaza/tools/datauri/index.php to generate base data URLs.

Here is a full example:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <script src="http://maps.google./maps/api/js?sensor=false" type="text/javascript"></script>
    </head>
    <body>
        <div id="map" style="width: 500px; height: 400px;"></div>
        <script type="text/javascript">
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10,
                center: new google.maps.LatLng(-33.92, 151.25),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var template = [
                '<?xml version="1.0"?>',
                    '<svg width="26px" height="26px" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3/2000/svg">',
                        '<circle stroke="#222" fill="{{ color }}" cx="50" cy="50" r="35"/>',
                    '</svg>'
                ].join('\n');
            var svg = template.replace('{{ color }}', '#800');

            var docMarker = new google.maps.Marker({
                position: new google.maps.LatLng(-33.92, 151.25),
                map: map,
                title: 'Dynamic SVG Marker',
                icon: { url: 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg) }
              });
        </script>
    </body>
</html>

Additional Information and an other solution using InfoBox can be found here.

Although this answer might be too late for you, it might help others looking for a solution to the same problem.

The HTML-elements representing the markers are not available via the API.

You must modify the property of the symbol(e.g. fillColor) and re-assign the modified symbol as icon-property of the marker:

var icon=marker.getIcon();
icon.fillColor='red';
marker.setIcon(icon); 

Demo(hover the symbol): http://jsfiddle/doktormolle/yxoy2zwe/

I did this by creating a SVG template for marker and then rendering the template to a Blob which I pass as blob url to google maps. Then redo the same process when you want to change attributes of the SVG.

This is far from optimal solution but it's one way to make it work. Unfortunately this method will make the icon to flicker if you update it frequently.

Example code:

var template = [
    '<?xml version="1.0"?>',
    '<svg width="26px" height="26px" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3/2000/svg">',
        '<circle stroke="#222" fill="{{ color }}" cx="50" cy="50" r="35"/>',
    '</svg>'
].join('\n');

var svg = template.replace('{{ color }}', '#888');
var blob = new Blob([svg], {type: 'image/svg+xml'});
var blobUrl = URL.createObjectURL(blob);

var image = {
    url: blobUrl,
    anchor: new google.maps.Point(13, 13)
};

var marker = new google.maps.Marker({
    position: map.getCenter(),
    map: map,  // Map object created earlier in the scope
    title: 'title',
    icon: image
});

// After finishing work with blob url, call:
// URL.revokeObjectURL(blobUrl);
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>