20

我已经构建了一个工具,允许人们将 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"}]}]"

(有关格式的更多文档)

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

到目前为止,我已经编写了这个 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)

...相反,它应该如下所示:

有格调的伦敦

有任何想法吗?谢谢!

4

5 回答 5

23

每个样式都必须提供一个单独的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('&');
  }

看结果

于 2013-10-01T13:23:51.283 回答
12

选择的答案对我不起作用。
但这只是因为我有一些没有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

于 2014-02-26T10:51:58.043 回答
5

这是一个做同样事情的 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

于 2015-01-27T14:47:55.423 回答
1

使用简单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);
于 2018-04-04T16:27:55.217 回答
0

我为所有 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('&');
}
于 2017-12-29T09:13:42.733 回答