Карты Google - работа с ключами API с помощью стилей JavaScript - PullRequest
0 голосов
/ 08 февраля 2019

Шаблон моего веб-сайта имеет довольно крутой стиль на карте Google, который прекрасно работал, пока Google не захотел, чтобы я получил код API.Получил код и карта работает с базовым стилем https://spcadbn.org.za/Untitled-1.html

Но не могу понять, как добавить код в мой скрипт Java, который выглядит следующим образом:

google.maps.event.addDomListener(window, 'load', init);

    var myLatlng = new google.maps.LatLng(-29.803562, 30.993815); 
    function init() {

        var myMapOptions = {

            zoom: 14,
            center: myLatlng,


            styles: [{
                "featureType": "water",
                "elementType": "all",
                "stylers": [{
                    "visibility": "on"
                }, {
                    "color": "#cdd9d9"
                }, {
                    "weight": 0.1
                }]
            }, {
                "featureType": "landscape",
                "elementType": "all",
                "stylers": [{
                    "visibility": "on"
                }, {
                    "saturation": -100
                }, {
                    "lightness": 65
                }]
            }, {
                "featureType": "poi",
                "elementType": "all",
                "stylers": [{
                    "visibility": "simplified"
                }, {
                    "saturation": -100
                }, {
                    "lightness": 51
                }]
            }, {
                "featureType": "road.highway",
                "elementType": "all",
                "stylers": [{
                    "visibility": "simplified"
                }, {
                    "saturation": -100
                }]
            }, {
                "featureType": "road.arterial",
                "elementType": "all",
                "stylers": [{
                    "visibility": "on"
                }, {
                    "saturation": -100
                }, {
                    "lightness": 30
                }]
            }, {
                "featureType": "road.local",
                "elementType": "all",
                "stylers": [{
                    "visibility": "on"
                }, {
                    "saturation": -100
                }, {
                    "lightness": 40
                }]
            }, {
                "featureType": "transit",
                "elementType": "all",
                "stylers": [{
                    "visibility": "simplified"
                }, {
                    "saturation": -100
                }]
            }, {
                "featureType": "administrative.province",
                "elementType": "all",
                "stylers": [{
                    "visibility": "off"
                }]
            }, {
                "featureType": "water",
                "elementType": "labels",
                "stylers": [{
                    "visibility": "on"
                }, {
                    "saturation": -100
                }, {
                    "lightness": -25
                }]
            }, {
                "featureType": "water",
                "elementType": "geometry",
                "stylers": [

                ]
            }, {
                "featureType": "road.arterial",
                "elementType": "geometry.stroke",
                "stylers": [{
                    "visibility": "on"
                }, {
                    "color": "#E6A329"
                }, {
                    "weight": 1
                }]
            }]
        };


        var mapElement = document.getElementById('map');

        var map = new google.maps.Map(mapElement, myMapOptions);
        var contentString = '<div id="content">' +
            '<div id="siteNotice">' +
            '</div>' +
            '<div id="mapInfoBox">' +
            '<br><h2 id="firstHeading" class="firstHeading">Find us</h2>' +
            '<h4><i class="fa fa-car text-primary"></i>&nbsp;&nbsp;&nbsp;&nbsp;<b>Cnr Inanda Rd/Willowfield Cres, Springfield Park</b></h4>' +
            '<h4><i class="fa fa-envelope text-primary"></i>&nbsp;&nbsp;&nbsp;&nbsp;<b>info@spcadbn.org.za</b></h4>' +
            '<h4><i class="fa fa-phone text-primary"></i>&nbsp;&nbsp;&nbsp;&nbsp;<b>+27 0 31 579 6500</b></h4><br>' +
            '<h4>Opening hours:</h4>' +
            '<p>Mon-Fri: 8am–4pm Saturday: 8am-12.30pm <br>Closed Sundays and public holidays</p>' +
            '</div>' +
            '</div>';
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            icon: 'img/map-marker.png',

        });
        google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
            infowindow.open(map, marker);
        });


    }

Ответы [ 2 ]

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

Для того, чтобы ваша карта работала правильно и не отображала сообщение об ошибке, вам необходимо убедиться, что скрипт API google включен перед любыми вызовами вашей собственной функции init - и, что более важно, API не требует *Параметр 1002 *, который часто встречается при вызове карты Google.Использование async и defer также больше не требуется при использовании google.maps.event.addDomListener(window, 'load', init); для создания экземпляра вашей карты - я думаю, что это личный выбор, какой метод вы выберете.

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>SPCA - Durban & Coast</title>
        <style>
            #map{width:80%;height:80vh;margin:auto;float:none;}
        </style>
        <!--
            As you are using `google.maps.event.addDomListener(window, 'load', init);` the script url below
            does not require the `callback` argument with, usually, `initMap`

            The actual code below is unchanged from that above in the question...
        -->
        <script src='//maps.googleapis.com/maps/api/js?key=<APIKEY>'></script>
        <script>
            google.maps.event.addDomListener(window, 'load', init);

                var myLatlng = new google.maps.LatLng(-29.803562, 30.993815); 
                function init() {

                    var myMapOptions = {

                        zoom: 14,
                        center: myLatlng,


                        styles: [{
                            "featureType": "water",
                            "elementType": "all",
                            "stylers": [{
                                "visibility": "on"
                            }, {
                                "color": "#cdd9d9"
                            }, {
                                "weight": 0.1
                            }]
                        }, {
                            "featureType": "landscape",
                            "elementType": "all",
                            "stylers": [{
                                "visibility": "on"
                            }, {
                                "saturation": -100
                            }, {
                                "lightness": 65
                            }]
                        }, {
                            "featureType": "poi",
                            "elementType": "all",
                            "stylers": [{
                                "visibility": "simplified"
                            }, {
                                "saturation": -100
                            }, {
                                "lightness": 51
                            }]
                        }, {
                            "featureType": "road.highway",
                            "elementType": "all",
                            "stylers": [{
                                "visibility": "simplified"
                            }, {
                                "saturation": -100
                            }]
                        }, {
                            "featureType": "road.arterial",
                            "elementType": "all",
                            "stylers": [{
                                "visibility": "on"
                            }, {
                                "saturation": -100
                            }, {
                                "lightness": 30
                            }]
                        }, {
                            "featureType": "road.local",
                            "elementType": "all",
                            "stylers": [{
                                "visibility": "on"
                            }, {
                                "saturation": -100
                            }, {
                                "lightness": 40
                            }]
                        }, {
                            "featureType": "transit",
                            "elementType": "all",
                            "stylers": [{
                                "visibility": "simplified"
                            }, {
                                "saturation": -100
                            }]
                        }, {
                            "featureType": "administrative.province",
                            "elementType": "all",
                            "stylers": [{
                                "visibility": "off"
                            }]
                        }, {
                            "featureType": "water",
                            "elementType": "labels",
                            "stylers": [{
                                "visibility": "on"
                            }, {
                                "saturation": -100
                            }, {
                                "lightness": -25
                            }]
                        }, {
                            "featureType": "water",
                            "elementType": "geometry",
                            "stylers": [

                            ]
                        }, {
                            "featureType": "road.arterial",
                            "elementType": "geometry.stroke",
                            "stylers": [{
                                "visibility": "on"
                            }, {
                                "color": "#E6A329"
                            }, {
                                "weight": 1
                            }]
                        }]
                    };


                    var mapElement = document.getElementById('map');

                    var map = new google.maps.Map(mapElement, myMapOptions);
                    var contentString = '<div id="content">' +
                        '<div id="siteNotice">' +
                        '</div>' +
                        '<div id="mapInfoBox">' +
                        '<br><h2 id="firstHeading" class="firstHeading">Find us</h2>' +
                        '<h4><i class="fa fa-car text-primary"></i>&nbsp;&nbsp;&nbsp;&nbsp;<b>Cnr Inanda Rd/Willowfield Cres, Springfield Park</b></h4>' +
                        '<h4><i class="fa fa-envelope text-primary"></i>&nbsp;&nbsp;&nbsp;&nbsp;<b>info@spcadbn.org.za</b></h4>' +
                        '<h4><i class="fa fa-phone text-primary"></i>&nbsp;&nbsp;&nbsp;&nbsp;<b>+27 0 31 579 6500</b></h4><br>' +
                        '<h4>Opening hours:</h4>' +
                        '<p>Mon-Fri: 8am–4pm Saturday: 8am-12.30pm <br>Closed Sundays and public holidays</p>' +
                        '</div>' +
                        '</div>';
                    var infowindow = new google.maps.InfoWindow({
                        content: contentString
                    });

                    var marker = new google.maps.Marker({
                        position: myLatlng,
                        map: map,
                        icon: 'img/map-marker.png',

                    });
                    google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
                        infowindow.open(map, marker);
                    });
                }
        </script>
    </head>
    <body>
        <!-- lots of other page content -->
        <div id='map'></div>
    </body>
</html>

Это было провереноиспользуя актуальный ключ и загруженный отлично - удачи.

Google Maps showing custom styles

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

Не используйте функцию init для события Window.Load.API будет вызывать обратный вызов в <script async defer src="https://maps.googleapis.com/maps/api/js?key=yourkey&callback=init"> всякий раз, когда API будет готов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...