Google maps 如何检查谷歌地图覆盖类型

Google maps 如何检查谷歌地图覆盖类型,google-maps,google-maps-api-3,Google Maps,Google Maps Api 3,可以检查谷歌地图覆盖的类型吗 var polygon = new G.Polygon(); var rectangle = new G.Rectangle(); var circle = new G.Circle(); var shape; 现在,我的代码将动态地将这些覆盖分配给shape变量 但是如何检测或检查名为shape的覆盖类型?我无法使用谷歌找到解决方案 您可以通过Javascript instanceof操作符检查类: var polygon = new G.Polygon();

可以检查谷歌地图覆盖的类型吗

var polygon = new G.Polygon();
var rectangle = new G.Rectangle();
var circle = new G.Circle();

var shape;
现在,我的代码将动态地将这些覆盖分配给
shape
变量


但是如何检测或检查名为
shape
的覆盖类型?我无法使用谷歌找到解决方案

您可以通过Javascript instanceof操作符检查类:

var polygon = new G.Polygon();
var rectangle = new G.Rectangle();
var circle = new G.Circle();

var shape = selectShape(polygon, rectangle, circle); // your dynamic selection funktion
if (shape instanceof G.Polygon) {
    alert("found Polygon");
}

您可以使用
instanceof
,但我建议不要这样做。它不是API的一部分,将来可能随时中断

最好在初始化时指定一个属性

var polygon = new G.Polygon();
polygon.type = 'polygon';

var rectangle = new G.Rectangle();
polygon.type = 'rectangle';

var circle = new G.Circle();
polygon.type = 'circle';

console.log(shape.type);

我编写了一个函数,返回给定的形状类型。它支持圆形和多边形,但我相信有人能想出如何添加矩形。它只需检查每个对象的唯一属性

function typeOfShape(shape){
    if(typeof shape.getPath === "function"){
        return "polygon";
    }else if(typeof shape.getRadius === "function"){
        return "circle";
    }else{
        return "unknown";
    }
}

instanceof不是API的一部分,但它是Javascript的一部分。它应该很好用,不一定。考虑这一点:<代码>函数标记(){{{}}};(新标记)标记的实例;/*false*/可能是因为标记的实例;/*假*/。。。。但是您需要检查(shape instanceof google.maps.Marker){//do something}。。。。那应该行得通,你没领会我的意思。如果API背后的代码以我演示的方式发生更改,
instanceof
将中断。