简体   繁体   中英

Google Maps API requires refresh to work correctly

I have problem coding the google maps API for my personal website. The google maps doesn't work until I refresh the browsers. Below are the scripts for google maps.

            <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&v3"></script>
            <script type="text/javascript" src="<?php echo get_bloginfo('template_url'); ?>/js/mk.js"></script>         

        <script type="text/javascript"> 

        var geocoder;
        var map;
        function initialize() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
          zoom: 13,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map"), myOptions);
        }

        function codeAddress(address) {

        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new MarkerWithLabel({

            position: results[0].geometry.location,
            map: map,
            labelContent: address,
            labelAnchor: new google.maps.Point(22, 0),
            labelClass: "labels", // the CSS class for the label
            labelStyle: {opacity: 1.0}

            });
            } else {
                //alert("Geocode was not successful for the following reason: " + status);
              }
            });
          }

        initialize();

        codeAddress("<?php 

            global $post;
            $pid = $post->ID;

            $terms = wp_get_post_terms($pid,'ad_location');
            foreach($terms as $term)
            {
                echo $term->name." ";
            }

            $location = get_post_meta($pid, "Location", true);  
            echo $location;

         ?>");

        </script> 

Did I missed anything for the scripts? I didn't add API on it, but the console said "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

You need to make sure the map variable is initialized before you pass it to markerOptions.

A bit of overzealous debugging showed me that on the times that the page fails, the map is still undefined.

The $(document).ready() will usually occur before body.onload, so either put a call to initialize() at the very top of your $(document).ready(function() { ... }); or put the code for initialize in there.

Also, though not strictly necessary, you should consider encapsulating your map variable instead of using a global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM