javascript中的范围错误,与功能有关[重复]

Posted

技术标签:

【中文标题】javascript中的范围错误,与功能有关[重复]【英文标题】:Error with scope in javascript, related to function [duplicate] 【发布时间】:2019-01-21 08:01:50 【问题描述】:

下面的代码理论上用于比较我已集成到网站中的所有 Google Maps API 书签,其中自定义书签的半径为 750 米,我正在尝试计算半径并知道它们是否重叠,并且为此,我一直在搜索互联网并增加了基本 APIv3 代码以及用于计算的 javascript 函数代码,以检查标记的光线是否相遇。

直到地图视图部分,显示在数据库表中注册的地址(共110个)加上地址保留地址(共5个)中的标记,但是在setMarkers()函数的末尾;我通过调用另一个函数 hasIntersections(); 增加了一个 for in;函数,然后“错误”发生。

由于我是 javascript 的初学者,我不知道如何修复,在控制台中显示的错误是,在 hasIntersections() 函数中;

“未捕获的类型错误:circle0.getCenter 不是函数”

<script async defer
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXX">
</script>

<script>
var geocoder;
var map;
var marker;
var image = 'https://www.keepidea.com.br/painel/assets/images/mark-teste.png';

var locations2 = [['RESERVA: ', -23.9446791, -46.3264323, 'Av. Senador Feijó, 421 - Vila Nova, Santos - SP, 11013-162, Brasil'],['RESERVA: ', , , 'R. Assunção, 414 - Sion, Belo Horizonte - MG, 30320-040, Brasil'],['RESERVA: ', , , 'R. Padre Feijó, 373 - Vila Tiberio, Ribeirão Preto - SP, 14050-360, Brasil'],['RESERVA: ', -23.0654964, -47.2263359, 'R. Vitoriano Salut, 72 - Chácara Belvedere, Indaiatuba - SP, Brasil'],['RESERVA: ', -20.8873894, -47.5997438, 'Rua Ana Luiza, 197 - Bairro Castelo, Batatais - SP, 14300-000, Brasil']];

var locations = [['Vila Osasco', -23.544559, -46.781034, 'Avenida Santo Antônio, 2761, Vila Osasco,  - SP, 06083-215, Brasil'],['Rebouças', -22.8904057, -43.5603237, 'Avenida Rebouças, 3657, Centro,  - SP, 13170-023, Brasil'],['Nutrition Bauru', -22.3370765, -49.0891827, 'Avenida Castelo Branco, 7-15, Vila Independência,  - SP, 17052-000, Brasil'],['Pitangueiras', -23.2022764, -46.8836439, 'Rua Pitangueiras, 790, Jardim Pitangueiras,  - SP, 13206-716, Brasil'],['Vale do Sol', -20.4229151, -49.9592271, 'Avenida pansani, 3092, Vale do sol,  - SP, 15500-302, Brasil'],['Cidade Nova Montes Claros-Mg', -16.739527, -43.8653989, 'Avenida Dona Gregória, 101, Cidade Nova,  - MG, 39400-464, Brasil'],['Centro Salto', -23.199741, -47.3008818, 'Avenida Dom Pedro II, 1421, Centro,  - SP, 13320-241, Brasil'],['ASSIS', -22.6575047, -50.397561, 'Rua Antônio da Silva Cunha Bueno, 425, Jardim Paulista,  - SP, 19815-080, Brasil'],['Paulinia', -22.743178, -47.1744984, 'Avenida João Aranha, 946, Alto de Pinheiros,  - SP, 13145-256, Brasil'],['SBC Centro', -23.7132318, -46.5532384, 'Rua Joaquim Nabuco, 56, Centro,  - SP, 09720-375, Brasil'],['Chácara', -23.6290144, -46.7025941, 'Rua da paz, 1498, Chácara Santo Antônio,  - SP, 04713-000, Brasil'],['Nova Europa', -22.9424831, -47.0573369, 'Avenida Baden Powell, 1831, Nova Europa,  - SP, 13040-093, Brasil'],['Morada do Sol', -23.1269188, -47.244239, 'Rua João Martini, 475, Jardim Morada do Sol,  - SP, 13348-350, Brasil'],['Campo grande RJ', -22.890374, -43.560187, 'Rua do petróleo, 14, Campo Gande,  - RJ, 23087-125, Brasil'],['Tremembé', -23.4587589, -46.6149244, 'Avenida Nova Cantareira, 4794, Tucuruvi,  - SP, 02340-002, Brasil'],['Vila das Belezas', -23.6491279, -46.7543918, 'Estrada de Itapecerica, 2219, Vila das Belezas,  - SP, 05835-005, Brasil'],['CCentro', -23.0854053, -47.2105986, 'Rua Humaitá, 1099, Centro,  - SP, 13339-140, Brasil'],['ITAPECERICA', -23.698334, -46.8527042, 'Rua Ari Batalha, 393, Parque Paraiso,  - SP, 06850-335, Brasil'],['lapa', -23.5250071, -46.6872423, 'Rua Clélia, 911, Lapa,  - SP, 05042-000, Brasil'],['Interação Flamboyant', -17.7718674, -48.6186493, 'Rua B-02, S/N, Estância Itanhanga,  - GO, 75690-000, Brasil'],['Tatuapé', -23.552282, -46.5566401, 'Rua Francisco Marengo, 1717, Tatuapé,  - SP, 03313-001, Brasil'],['Flamboyant', -22.8762222, -47.0358206, 'Rua Comendador Doutor Antônio Pompeo Camargo, 104, Jardim Boa Esperança,  - SP, 13091-502, Brasil'],['N.Sr de Fatima', -22.8975439, -47.1685964, 'Armelinda Espúrio da Silva, 565, Jardim Nossa Senhora de Fátima,  - SP, 13084-450, Brasil'],['Agapeama', -23.2053398, -46.8651296, 'Rua da Varzea Paulista, 487, Vila Agricola,  - SP, 13202-700, Brasil'],['Buriti', -23.2230818, -46.8760877, 'Rua Dom Pedro I, 462, Jardim Buriti,  - SP, 13225-790, Brasil'],['BOA VISTA', -14.8793362, -40.832031, 'Avenida Gilenilda Alves, 1345, Boa Vista,  - BA, 45027-560, Brasil'],['FABRICA DE RESULTADOS', -23.6008617, -46.8988726, 'Rua Pinhal, 83, Jardim Sabia,  - SP, 06716-575, Brasil'],['Valentina Cross Life',-16.7287284, -43.8835938, 'Rua Espírito Santo Esplanada, 395, Esplanada,  - MG, 39401-452, Brasil'],['PEDRO PINHO', -23.5402247, -46.8010548, 'Avenida General Pedro Pinho, 1052, Pestana,  - SP, 06122-160, Brasil']];

function initMap()

    var latlng = new google.maps.LatLng(-84.568808, -100.418683);
    var options = 
        zoom: 4,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    ;
    map = new google.maps.Map(document.getElementById("mapa"), options);
    geocoder = new google.maps.Geocoder();
    marker = new google.maps.Marker(
        map: map,
        zoom: 4
    );
    marker.setPosition(latlng);
    setMarkers(map,locations);
    setMarkers(map,locations2);


Number.prototype.toRadians = function() 
    return this * (Math.PI / 180.0);
;

function distance(lat0, long0, lat1, long1)

    var rlat0 = lat0.toRadians();
    var rlong0 = long0.toRadians();
    var rlat1 = lat1.toRadians();
    var rlong1 = long1.toRadians();
    var deltaLat = (rlat1-rlat0);
    var deltaLong = (rlong1-rlong0);
    var a = Math.pow(Math.sin(deltaLat / 2), 2) + Math.pow( Math.sin(deltaLong / 2), 2) * Math.cos(rlat0) * Math.cos(rlat1);  
    return (2 * Math.asin(Math.sqrt(a))) * 6378137;


function hasIntersections(circle0,circle1)

    var center0 = circle0.getCenter();
    var center1 = circle1.getCenter();
    var maxDist = circle0.getRadius()+circle1.getRadius();
    var actualDist = distance(center0.lat(),center0.lng(),center1.lat(),center1.lng());
    return maxDist>=actualDist;


circles = [];
circles2 = [];
circle = null;
circle2 = null;

function setMarkers(map,locations)


    var marker = null;
    var i = null;

    for (i = 0; i < locations.length; i++)
    
        var loan = locations[i][0]
        var lat = locations[i][1]
        var long = locations[i][2]
        var add =  locations[i][3]
        latlngset = new google.maps.LatLng(lat, long);

        var marker = new google.maps.Marker(  
            map: map,
            title: loan,
            position: latlngset,
            icon: image
        );

        var cityCircle = new google.maps.Circle(
            map: map,
            zoom: 4,
            center: new google.maps.LatLng(lat, long),
            radius: 750,
            strokeColor: "#818c99",
            fillColor: "#ffffff",
            fillOpacity: 0.50
        );

        circles.push(cityCircle);

        map.setCenter(marker.getPosition());
        var content = "<h5>" + loan + '</h5>' + "<strong>Endereço:</strong> " + add;
        var infowindow = new google.maps.InfoWindow()
        google.maps.event.addListener(marker,'click', (function(marker,content,infowindow) 
            return function()
            
                infowindow.setContent(content);
                infowindow.open(map,marker);
            ;
        )(marker,content,infowindow));

    

    var marker = null;
    var i = null;

    for (i = 0; i < locations2.length; i++)
    
        var loan = locations2[i][0]
        var lat = locations2[i][1]
        var long = locations2[i][2]
        var add =  locations2[i][3]
        latlngset = new google.maps.LatLng(lat, long);
        var marker = new google.maps.Marker(  
            map: map,
            title: loan,
            position: latlngset,
            icon: image
        );

        var cityCircle = new google.maps.Circle(
            map: map,
            zoom: 4,
            center: new google.maps.LatLng(lat, long),
            radius: 750,
            strokeColor: "#229A1F",
            fillColor: "#49DA45",
            fillOpacity: 0.50
        );

        circles2.push(cityCircle);

        map.setCenter(marker.getPosition());
        var content = "<h5>" + loan + '</h5>' + "<strong>Endereço:</strong> " + add;
        var infowindow = new google.maps.InfoWindow()
        google.maps.event.addListener(marker,'click', (function(marker,content,infowindow) 
            return function() 
                infowindow.setContent(content);
                infowindow.open(map,marker);
            ;
        )(marker,content,infowindow));
    

    for ( var circle1 in circles )
    
        for ( var circle2 in circles2 )
        
            console.log(hasIntersections(circle1, circle2)); 
        
    

</script>

我在控制台上做了一个测试,用console.log(圈子),结果一共5个结果如下:

_.qg gm_accessors_:…,地图:gg,gm_bindings_:…,缩放:4,中心:_.L,… A: .Rw Ck: 0, e3: …, b: "planetRadius", f: false, getPlanetRadius: ƒ, … center : _.L lat: ƒ, lng: ƒclosure_uid_660309532 : 1199 draggable_changed : ƒ c() editable_changed : ƒ e() f : gg gm_bindings_: …, __gm: Cf, gm_accessors_:…,缩放:4,中心:_.L,… 填充颜色:“#49DA45” 填充不透明度: 0.5 gm_accessors_ : map: null, zoom: null, center: null, radius: null, strokeColor: null, ... gm_bindings_ : map: ..., zoom: ..., 中心:...,半径:...,strokeColor:...,... hh:hW Ck:0,__e3_: …, b: _.sg, gm_bindings_: …, gm_accessors_: …, … ja : (9) [Mc, Mc,Mc,Mc,Mc,Mc,Mc,Mc,Mc] 映射:gg gm_bindings_:…,__gm:Cf, gm_accessors_:...,缩放:4,中心:_.L,... 半径:750 strokeColor :“#229A1F”vh:(3)[Mc,Mc,Mc]可见:真实缩放:4 __e3_ : 工具栏:…,鼠标悬停:…,单击:…,鼠标悬停:… __proto : 对象

console.log (circles2) 的结果是总共 110,对于 circles 和 circles2 的值节拍,因为对于 var location [] 有 109 和 var location [] 有 5,总共 115,这已经注册在数据库数据中。

【问题讨论】:

for...in 更改为for...of @PatrickRoberts 嘿,最大的,它工作得很好,非常感谢! 解释是 for in 循环遍历数组内的所有属性,包括那些不是圆形的。因此,当 for in 循环尝试将非圆形与圆形进行比较时,您会得到错误。 【参考方案1】:

如果你在hasIntersections() 中使用console.log(circle0, circle1),你可能会得到0, 1, 2, ...,因为这是你使用for (a in array) 时得到的。

要修复它,可以这样称呼它:

for ( var circle1 in circles )
    
        for ( var circle2 in circles2 )
        
            console.log(hasIntersections(circles[circle1], circles2[circle2])); 
        
    

【讨论】:

没用,谢谢,抱歉! 什么不起作用? 返回另一个错误,无法识别getCenter(); @Patrick 上面的答案解决了这个问题。感谢。

以上是关于javascript中的范围错误,与功能有关[重复]的主要内容,如果未能解决你的问题,请参考以下文章

等效于 Javascript 中的 python 范围 [重复]

javascript正则表达式数字范围格式检查[重复]

JavaScript短路仍然引发未定义的错误[重复]

Javascript 范围——var vs global

将 fetch 与 Content-Type 一起使用时出现 CORS 错误 [重复]

如何限制javascript / jquery中函数的范围[重复]