Новая карта Google: LatLng не число, но я думаю, что это - PullRequest
0 голосов
/ 03 февраля 2019

Попытка заставить это работать - https://clinicalthermography.co.nz/test_map.php

например, 1-ое местоположение регистрируется как

"Object
Lat: -36.768498
Lng: 174.75895"

Но ошибка говорит, что lat не число.Вместо того, чтобы возиться слепо, этот новичок хотел бы понять, почему это не так и что это: -)

var map, marker;

function initMap() {
    geocoder = new google.maps.Geocoder();

    var centerOfNZ = {lat: -40.8, lng: 173.0};
        map = new google.maps.Map(document.getElementById('map'), {
        zoom: 5.9,
        center: centerOfNZ
    });

    markAllLocations ();
}

function markAllLocations () {
    var locations = [
        ['Auckland','Milford Health Clinic, 50 East Coast Road, Milford', -36.768498, 174.75895],
        ['Christchurch',     'The George, 50 Park Terrace, Christchurch', -43.525776, 172.628387],
        ['Dunedin',          'Aurora on George, 678 George St,   Dunedin', -45.876251, 170.502548],
        ['Hamilton ',        'Medcom Integrative Health Clinic, 32 O\'Neill St, Claudelands,  Hamilton', -37.781234, 175.288198],
        ['Hawke\'s Bay',      'The Doctors Greenmeadows, 524 Kennedy Rd,  Greenmeadows,  Napier', -39.5229328, 176.8685695],
        ['Invercargill',     'The Quest Serviced Apartments, 10 Dee St,  Cnr Dee and Tay Streets,  Invercargill', -46.4131866, 168.3537731],
        ['Nelson',           'Delorenzos Apartments, 43\-55 Trafalgar St,  The Wood,  Nelson', -41.267575, 173.287417],
        ['New Plymouth',     'Quality Hotel Plymouth, Cnr of Courtney and Leach St,  New Plymouth', -39.061173, 174.06889],
        ['Palmerston North', 'Cornwall Motor Lodge, 101 Fitzherbert Avenue,  Palmerston North', -40.3596103, 175.6141897],
        ['Queenstown',       'Level One, 5 Duke St,  Queenstown', -45.03135700, 168.65935960],
        ['Tauranga',         '1416A Cameron Rd Greerton,  Tauranga', -37.729565, 176.129608],
        ['Wanaka',           'C/- Janice Cleghorne, 143 Hunter Cres,  Wanaka', -44.697945,169.167267],
        ['Wellington',       'The Quest on Thorndon, 61\-63 Thorndon Quay,  Thorndon,  Wellington', -41.2760045, 174.7813852],
        ['Whangarei',        'Distinction Whangarei Hotel, 9 Riverside Drive,  Riverside,  Whangarei', -35.723466, 174.327632]
    ];

    for (let count = 0; count < locations.length; count++) {
        let myPos = {                     
                Lat : locations[count][2],
                Lng : locations[count][3]
        };
        console.log(
            count + '  ' + locations[count][0] 
        );
        console.log(myPos);

        marker = new google.maps.Marker(
            { map : map,
              position: myPos,  
              title: locations[count][0] 
            }
        );
    }
}

Ответы [ 2 ]

0 голосов
/ 03 февраля 2019

Как вы, возможно, уже поняли, произошла небольшая неточность в написании, которая привела к ошибке, с которой вы столкнулись.Правильное написание lat и lng ~ все строчные, а не прописные.Тем не менее, не мешало бы преобразовывать переменные в числа при вызове их с помощью parseFloat(var) или с помощью метода карт Google new google.maps.LatLng(_LAT_,_LNG_)

Поскольку у меня было немного свободного времени, я поиграл с оригинальным кодомнемного, как вы увидите ниже - надеюсь, это поможет.

<!DOCTYPE html>
<html>
    <head>
        <title>Google Maps: New Zealand - Clinical Thermography</title>
        <meta charset="utf-8" />
        <style>
            body,
            html { height:100%;margin:0;padding:0;box-sizing:border-box; }
            #map { width:90%;height:90vh; margin:auto;float:none; }
            /* hide infowindow & pre-format content */
            #info{display:none; padding:1rem;margin:0.25rem;border:1px solid pink;background:white;}
            #info div{margin:0.5rem auto;}
            #info div:before{content:attr(data-label)":";text-transform:capitalize;font-weight:bold;color:black;margin:0 0.5rem 0 0;}
            #info div:after{content:attr(data-value);color:pink;}
        </style>
        <script>
            let map;
            let marker;
            let infoWindow;
            let geocoder;
            let content;

            function initMap() {
                const centerOfNZ = {
                        lat: -40.8,
                        lng: 173.0
                    };
                map = new google.maps.Map( document.getElementById('map'), {
                    zoom: 5.9,
                    center: centerOfNZ
                });

                /* The Geocoder is not used */
                //geocoder = new google.maps.Geocoder();


                infoWindow = new google.maps.InfoWindow({ maxWidth:350, disableAutoPan:false });
                infoWindow.setContent( document.getElementById('info') );

                markAllLocations();
            }

            function markAllLocations () {
                let locations = [
                    ['Auckland',            'Milford Health Clinic, 50 East Coast Road, Milford', -36.768498, 174.75895],
                    ['Christchurch',        'The George, 50 Park Terrace, Christchurch', -43.525776, 172.628387],
                    ['Dunedin',             'Aurora on George, 678 George St,   Dunedin', -45.876251, 170.502548],
                    ['Hamilton ',           'Medcom Integrative Health Clinic, 32 O\'Neill St, Claudelands,  Hamilton', -37.781234, 175.288198],
                    ['Hawke\'s Bay',        'The Doctors Greenmeadows, 524 Kennedy Rd,  Greenmeadows,  Napier', -39.5229328, 176.8685695],
                    ['Invercargill',        'The Quest Serviced Apartments, 10 Dee St,  Cnr Dee and Tay Streets,  Invercargill', -46.4131866, 168.3537731],
                    ['Nelson',              'Delorenzos Apartments, 43\-55 Trafalgar St,  The Wood,  Nelson', -41.267575, 173.287417],
                    ['New Plymouth',        'Quality Hotel Plymouth, Cnr of Courtney and Leach St,  New Plymouth', -39.061173, 174.06889],
                    ['Palmerston North',    'Cornwall Motor Lodge, 101 Fitzherbert Avenue,  Palmerston North', -40.3596103, 175.6141897],
                    ['Queenstown',          'Level One, 5 Duke St,  Queenstown', -45.03135700, 168.65935960],
                    ['Tauranga',            '1416A Cameron Rd Greerton,  Tauranga', -37.729565, 176.129608],
                    ['Wanaka',              'C/- Janice Cleghorne, 143 Hunter Cres,  Wanaka', -44.697945,169.167267],
                    ['Wellington',          'The Quest on Thorndon, 61\-63 Thorndon Quay,  Thorndon,  Wellington', -41.2760045, 174.7813852],
                    ['Whangarei',           'Distinction Whangarei Hotel, 9 Riverside Drive,  Riverside,  Whangarei', -35.723466, 174.327632]
                ];

                /* easier to use `forEach` as the source is an array */
                locations.forEach( location => {
                    /*
                        use `parseFloat` to cast the string to a number/float
                        Alternatively, use `new google.maps.LatLng(location[2],location[3])` 
                        which will do it all nicely for you
                    */
                    marker = new google.maps.Marker({ 
                        map : map,
                        title: location[0],
                        description:location[1],
                        position: {
                            lat: parseFloat( location[2] ),
                            lng: parseFloat( location[3] )
                        }
                    });
                    /* show info for each marker when clicked */
                    google.maps.event.addListener( marker, 'click', function(e){
                        /* get a reference to the infowindow content */
                        content=infoWindow.getContent();
                        /* ensure the content is visible */
                        content.style.display='block';
                        /* add details from marker to the content */
                        content.querySelector('[data-label="name"]').dataset.value=this.title;
                        content.querySelector('[data-label="description"]').dataset.value=this.description;
                        content.querySelector('[data-label="co-ordinates"]').dataset.value=[this.position.lat(),this.position.lng()].join(', ');
                        /* display content */
                        infoWindow.setPosition( e.latLng );
                        infoWindow.open( map );
                    });
                });

            }
        </script>
        <script src='//maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap' async defer></script>
    </head>
    <body>
      <div id='map'></div>
      <!-- use a hidden element as the content for the infoWindow content -->
      <div id='info'>
        <div data-label='name' data-value=''></div>
        <div data-label='description' data-value=''></div>
        <div data-label='co-ordinates' data-value=''></div>
      </div>
    </body>
</html>
0 голосов
/ 03 февраля 2019

API Карт Google Marker() необходимо передать объект position с ключами lng и lat, оба из которых имеют числовые значения.В вашем случае у вас есть объект myPos с Lat и Lng (заглавными буквами), и вы получаете сообщение об ошибке, потому что myPos.lat === undefined.

...