【问题标题】:Converting Google Maps styles array to Google Static Maps styles string将 Google 地图样式数组转换为 Google 静态地图样式字符串
【发布时间】:2013-10-07 13:20:45
【问题描述】:

我已经构建了一个工具,允许人们将 JSON 地图样式应用于 Google 地图,现在我想添加对 Google Static Maps API 的支持。

使用以下样式数组:

"[{"stylers":[]},{"featureType":"water","stylers":[{"color":"#d2dce6"}]},{"featureType":"administrative.country","elementType":"geometry","stylers":[{"weight":1},{"color":"#d5858f"}]},{"featureType":"administrative.country","elementType":"labels.text.fill","stylers":[{"color":"#555555"}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"administrative.country","stylers":[{"visibility":"on"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"simplified"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"landscape","elementType":"all","stylers":[{"hue":"#FFFFFF"},{"saturation":-100},{"lightness":100}]},{"featureType":"landscape.natural","elementType":"geometry","stylers":[{"saturation":-100}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"visibility":"simplified"},{"saturation":-100}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"saturation":-100},{"lightness":60}]},{"featureType":"poi","elementType":"geometry","stylers":[{"hue":"#FFFFFF"},{"saturation":-100},{"lightness":100},{"visibility":"off"}]}]"

(More documentation on format)

我最终需要将其转换为 URLescaped 字符串,格式为:style=feature:featureArgument|element:elementArgument|rule1:rule1Argument|rule2:rule2Argument(More documentation)

到目前为止,我已经编写了这个 JavaScript 来尝试转换,但它不能正常工作:

  function get_static_style(styles) {
    var result = '';
    styles.forEach(function(v, i, a){
      if (v.stylers.length > 0) { // Needs to have a style rule to be valid.
        result += (v.hasOwnProperty('featureType') ? 'feature:' + v.featureType : 'feature:all') + '|';
        result += (v.hasOwnProperty('elementType') ? 'element:' + v.elementType : 'element:all') + '|';
        v.stylers.forEach(function(val, i, a){
          var propertyname = Object.keys(val)[0];
          var propertyval = new String(val[propertyname]).replace('#', '0x');
          result += propertyname + ':' + propertyval + '|';
        });
      }
    });
    console.log(result);
    return encodeURIComponent(result);
  }

唉,这段代码输出如下:

(右键单击并选择“复制 URL”以查看我正在使用的完整路径——以上是直接来自静态图像 API)

...相反,它应该是这样的:

有什么想法吗?谢谢!

【问题讨论】:

    标签: javascript google-maps google-maps-api-3 google-static-maps


    【解决方案1】:

    必须为每个样式提供单独的style-参数:

     function get_static_style(styles) {
        var result = [];
        styles.forEach(function(v, i, a){
          var style='';
          if (v.stylers.length > 0) { // Needs to have a style rule to be valid.
            style += (v.hasOwnProperty('featureType') ? 'feature:' + v.featureType : 'feature:all') + '|';
            style += (v.hasOwnProperty('elementType') ? 'element:' + v.elementType : 'element:all') + '|';
            v.stylers.forEach(function(val, i, a){
              var propertyname = Object.keys(val)[0];
              var propertyval = val[propertyname].toString().replace('#', '0x');
              style += propertyname + ':' + propertyval + '|';
            });
          }
          result.push('style='+encodeURIComponent(style))
        });
    
        return result.join('&');
      }
    

    watch the result

    【讨论】:

    • 啊!现在这完全有道理。谢谢!
    【解决方案2】:

    所选答案对我不起作用。
    但只是因为我有一些没有styler 参数的对象。
    我不得不像这样修改它:

    function get_static_style(styles) {
        var result = [];
        styles.forEach(function(v, i, a){
    
            var style='';
            if( v.stylers ) { // only if there is a styler object
                if (v.stylers.length > 0) { // Needs to have a style rule to be valid.
                    style += (v.hasOwnProperty('featureType') ? 'feature:' + v.featureType : 'feature:all') + '|';
                    style += (v.hasOwnProperty('elementType') ? 'element:' + v.elementType : 'element:all') + '|';
                    v.stylers.forEach(function(val, i, a){
                        var propertyname = Object.keys(val)[0];
                        var propertyval = val[propertyname].toString().replace('#', '0x');
                        // changed "new String()" based on: http://stackoverflow.com/a/5821991/1121532
    
                        style += propertyname + ':' + propertyval + '|';
                    });
                }
            }
            result.push('style='+encodeURIComponent(style));
        });
    
        return result.join('&');
    }
    

    查看实际操作:http://jsfiddle.net/ZnGpb/1/

    ps:JSHint

    【讨论】:

    • 这对我来说效果很好。图书馆的一个很好的功能。
    【解决方案3】:

    这是一个做同样事情的 PHP 方法

    public function mapStylesUrlArgs($mapStyleJson)
    {
        $params = [];
    
        foreach (json_decode($mapStyleJson, true) as $style) {
            $styleString = '';
    
            if (isset($style['stylers']) && count($style['stylers']) > 0) {
                $styleString .= (isset($style['featureType']) ? ('feature:' . $style['featureType']) : 'feature:all') . '|';
                $styleString .= (isset($style['elementType']) ? ('element:' . $style['elementType']) : 'element:all') . '|';
    
                foreach ($style['stylers'] as $styler) {
                    $propertyname = array_keys($styler)[0];
                    $propertyval = str_replace('#', '0x', $styler[$propertyname]);
                    $styleString .= $propertyname . ':' . $propertyval . '|';
                }
            }
    
            $styleString = substr($styleString, 0, strlen($styleString) - 1);
    
            $params[] = 'style=' . $styleString;
        }
    
        return implode("&", $params);
    }
    

    源代码:https://gist.github.com/WouterDS/5942b891cdad4fc90f40

    【讨论】:

    • 正是我所需要的。谢谢!
    【解决方案4】:

    使用简单的map:

    // Given styles array
    const myStyles = [
    {
      elementType: 'geometry',
      stylers: [
        {
          color: '#f5f5f5'
        }
      ]
    },
    {
      elementType: 'labels.icon',
      stylers: [
        {
          visibility: 'off'
        }
      ]
    },
    {
      elementType: 'labels.text.fill',
      stylers: [
        {
          color: '#616161'
        }
      ]
    },
    {
      elementType: 'labels.text.stroke',
      stylers: [
        {
          color: '#f5f5f5'
        }
      ]
    },
    {
      featureType: 'administrative',
      elementType: 'geometry',
      stylers: [
        {
          visibility: 'off'
        }
      ]
    },
    {
      featureType: 'administrative.land_parcel',
      elementType: 'labels.text.fill',
      stylers: [
        {
          color: '#bdbdbd'
        }
      ]
    }];
    
    const buildStyles = (styles) => {
      return styles.map((val, idx) => {
        const { featureType, elementType, stylers } = val;
        const feature = `feature:${featureType || 'all'}`;
        const element = `element:${elementType || 'all'}`;
        const styles = stylers.map(style => {
          const name = Object.keys(style)[0];
          const val = styles[name].replace('#', '0x');
          return `${name}:${val}`;
        });
    
        return `style=${encodeURIComponent(`${feature}|${element}|${styles}|`)}`;
      }).join('&');
    };
    
    const stylesStr = buildStyles(myStyles);
    

    【讨论】:

    • 谢谢。这个解决方案对我有用,除了一个小错误: const val = styles[name].replace('#', '0x');应为: const val = style[name].replace('#', '0x');
    【解决方案5】:

    我为所有 Android 开发者创建了这个实用的 nodejs 函数。

    保存下面的代码为flatten-mapstyle.jsanyware。

    运行使用:node flatten-mapstyle.js /path/to/your/style/style_json.json

    urlencode 输出使用-e 标志,即:node flatten-mapstyle.js style_json.json -e

    const fs = require('fs');
    const {promisify} = require('util');
    
    const args = process.argv.slice(2)
    
    const filename = args[0]
    const encode = args[1]
    
    const exists = promisify(fs.exists);
    const readFile = promisify(fs.readFile);
    
    
    async function main() {
        try {
            if (filename == undefined || await !exists(filename)) {
                throw {
                    'error': `file ${filename} does not exist`
                }
            }
            let json = await readFile(filename, 'utf8');
            console.log("=========COPY BELOW========")
            console.log(getStaticStyle(JSON.parse(json)))
            console.log("=========END OF COPY========")
        } catch (e) {
            console.error(e);
        }
    }
    
    main();
    
    function getStaticStyle(styles) {
        var result = [];
        styles.forEach(function(v, i, a) {
    
            var style = '';
            if (v.stylers) { // only if there is a styler object
                if (v.stylers.length > 0) { // Needs to have a style rule to be valid.
                    style += (v.hasOwnProperty('featureType') ? 'feature:' + v.featureType : 'feature:all') + '|';
                    style += (v.hasOwnProperty('elementType') ? 'element:' + v.elementType : 'element:all') + '|';
                    v.stylers.forEach(function(val, i, a) {
                        var propertyname = Object.keys(val)[0];
                        var propertyval = val[propertyname].toString().replace('#', '0x');
                        style += propertyname + ':' + propertyval + '|';
                    });
                }
            }
            result.push('style=' + (encode == "-e" ? encodeURIComponent(style) : style));
        });
    
        return result.join('&');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多