Scope Help in Javascript

Asked

Viewed 78 times

-2

The code below serves theoretically to compare all the markers from the Google Maps API I’ve integrated to the website, where the custom markers have a radius of 750 meters, and I’m trying to calculate the radius and see if they overlap, and for that I searched the internet and incremented the basic code of Apiv3 and more the code of the functions javascript for the calculation to verify if the rays of the markers are found.

Up to the map view part, the markers in the addresses registered in the database table (110 total) plus the address reservation addresses (5 total) were displayed, but at the end of the setMarkers function(); incremented a for in calling another function, the function hasIntersections();, and then what happens the "mistake".

Since I’m beginner in javascript I don’t know how to fix, in the console the error displayed is, which is in the function hasIntersections();

"Uncaught Typeerror: circle0.getCenter is not a Function"

<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>

I did a test on the console, with console.log(Circles), and the result was a total of 5 results as:

_.qg {gm_accessors_: {...}, map: Gg, gm_bindings_: {...}, zoom: 4, center: _.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_: {...}, zoom: 4, center: _.L, ... } fillColor : "#49DA45" fillOpacity : 0.5gm_accessors_ : {map: null, zoom: null, center: null, Radius: null, strokeColor: null, ... } gm_bindings_ : {map: {...}, zoom: {...}, center: {...}, Radius: {...}, strokeColor: {...}, ... } hh : hw {Ck: 0, __e3_: {... }, b: _.Sg, gm_bindings_: {...}, gm_accessors_: {...}, ... } ja : (9) [Mc, Mc, Mc, Mc, Mc, Mc, Mc, Mc, Mc] map : Gg {gm_bindings_: {...}, __gm: Cf, gm_accessors_: {...}, zoom: 4, center: _.L, ... } Radius : 750 strokeColor : "#229A1F" vh : (3) [Mc, Mc, Mc] Visible : true zoom : 4 __e3_ : {Toolbar: {...}, mouseover: {...}, click: {...}, mouseout: {...}} __proto : Object

And for console.log(circles2) the result in total of 110, for Circles and circles2 the values hit, because for var Location[] has 109 and var Location[] has 5, total of 115, which has registered in the database.

  • 1

    Have you, by any chance, checked the values of circle1 and circle2 that you passed by parameter to hasIntersections?

  • @Andersoncarloswoss I incremented the result of the arrays and below the javascript code one of the console results.

1 answer

0

I solved the code at the end of the function by changing the for in for for of in the setMarkers() function with the help of the community SO_EN;

<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 of circles )
    {
        for ( var circle2 of circles2 )
        {
            console.log(hasIntersections(circle1, circle2)); 
        }
    }
}
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.