Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将Google地图样式数组转换为Google静态地图样式字符串_Javascript_Google Maps_Google Maps Api 3_Google Static Maps - Fatal编程技术网

Javascript 将Google地图样式数组转换为Google静态地图样式字符串

Javascript 将Google地图样式数组转换为Google静态地图样式字符串,javascript,google-maps,google-maps-api-3,google-static-maps,Javascript,Google Maps,Google Maps Api 3,Google Static Maps,我已经构建了一个工具,允许人们将JSON映射样式应用于Google映射,现在我想添加对该样式的支持 使用以下样式数组: [{stylers:[]},{featureType:water,stylers:[{color:d2dce6}]},{featureType:administrative.country,elementType:geometry,stylers:[{weight:1},{color:D585858F}},{featureType:administrative.country,

我已经构建了一个工具,允许人们将JSON映射样式应用于Google映射,现在我想添加对该样式的支持

使用以下样式数组:

[{stylers:[]},{featureType:water,stylers:[{color:d2dce6}]},{featureType:administrative.country,elementType:geometry,stylers:[{weight:1},{color:D585858F}},{featureType:administrative.country,elementType:labels.text.fill,stylers:[{color:55555555}},{featureType:administrative,elementType:geometry.stroke,stylers:[{visibility:off},{featureType:administration.country,stylers:[{visibility:on}]},{featureType:road.highway,stylers:[{saturation:100},{lightness:40},{visibility:simplified}},{featureType:road.artery,stylers:[{{saturation:-100},{lightness:40},{visibility:simplified}]},{featureType:road.local saturation:100},{visibility:simplified},{featureType:scape,elementType:all,stylers:[{hue:FFFFFF},{saturation:-100},{lightness:100}]},{featureType:scape.natural,elementType:geometry,stylers:[{saturation:-100}]},{featureType:scape.人造,elementType:geometry.fill,stylers:[{可见性:简化},{saturation:-100}},{featureType:poi.park,elementType:geometry,stylers:[{saturation:-100},{lightness:60}]},{featureType:poi,elementType:geometry,stylers:[{hue:ffffffff},{saturation:-100},{lightness:100},{visibility:off}]}]

我需要最终将其转换为URL转义字符串,格式为: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

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


有什么想法吗?谢谢!

每个样式都必须提供一个单独的样式参数:

 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('&');
  }

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

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('&');
}
请访问以下网址查看它的实际应用:


p、 s:JSHint

这是一个执行相同操作的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);
}

src:

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

将下面的代码另存为flant-mapstyle.js anyware

运行时使用:node flant-mapstyle.js/path/to/your/style/style\u json.json

要对输出进行URL编码,请使用-e标志,即:node flant-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('&');
}
// 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);