Home > front end >  Javascript WebMap Using a Google API Not Functioning
Javascript WebMap Using a Google API Not Functioning

Time:02-04

I am currently working on a JavaScript web map that is powered by GoogleAPI. The map works with a Google geocoder and drops a pin on the location that the user has entered in the search address box. A radius is placed around the pin if the user would like to show how close they are to a location on the map up to fifty miles. I also have the function spiderfier in the code for pins that are overlapping. The map was working fine on my device and all functionality was working as well, but I am now receiving an error message that says "ReferenceError: google is not defined". I have marked in the code where this is occurring. This happened when I began trying to fix the code so the map could appear on other colleagues' computers. The solutions I tried to use included fixing the order of the API key and other packages, using a new API key, disabling Ad-Blocker, and clearing the cookies and cache. I also tried to change the order of the last line of code, moving the problematic line of code to before the line of code where the markers are created. I have put the code I am using below along with the error that others and myself are receiving on our computers. I also put links to some of the solutions I tried.

<!DOCTYPE html>
<html>

<head>
    <meta charset=utf-8 />
    
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />

  <script src="https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier/1.0.3/oms.min.js"></script>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
    
       <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY_HERE&callback=initAutocomplete&libraries=places&v=weekly&channel=2"
      async></script>

    
     <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
    
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    
    
<div id="map" style="height: 100%; width: 100%; position: absolute; top: 0px; left: 0px; "></div>
    <div id="sidebar" style = "float:right; top:right"></div>
    
        

<input id="searchtext" type="text" value=" "  placeholder="Enter search location here" style="z-index: 0; position: absolute; left: 125px; top: 0px;">

<div id="searchcontainer" style="position: absolute; z-index: 0; left: 450px; top: 0px;">
  <select id="range" name="range">
        <option value="0">Current Map</option>
        <option value="5">5 Miles</option>
        <option value="10">10 Miles</option>
        <option value="15">15 Miles</option>
        <option value="20">20 Miles</option>
        <option value="25">25 Miles</option>
        <option value="50">50 Miles</option>
    </select>

</div>

    <style>
        html,
body,
        
        
#container {
  height: 100%;
  display: flex;
}
#map {
  height: 100%;
  margin: 0;
  padding: 0;
  width: 100%;
}
        

    </style>
</head>

<body>

<script>

var METERS_PER_MILE = 1609.34;
   

function myMap() {
  var myCenter = new google.maps.LatLng(41.493430, -103.996772);
  var mapProp = {
    center: myCenter,
    zoom: 4,
    scrollwheel: true,
    draggable: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  
  var map = new google.maps.Map(document.getElementById("map"), mapProp);
  var circle;
  google.maps.event.addDomListener(document.getElementById('range'), 'change', function(evt) {
    var value = $("#range").val();
    if (circle && circle.setMap) circle.setMap(null);
    var center = map.getCenter();
    if (markers.length > 0) center = markers[0].getPosition();
    circle = new google.maps.Circle({
      center: center,
      radius: value * METERS_PER_MILE,
      map: map
    });
    map.fitBounds(circle.getBounds());
  });
    
    
   var markers = [
       
       {'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '27.4922222222222',
'lng':  '-99.4641666666667'},
{'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '27.4922222222222',
'lng':  '-99.4641666666667'},
{'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '27.4922222222222',
'lng':  '-99.4641666666667'},
{'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '28.2336111111111',
'lng':  '-82.1811111111111'},
{'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '28.2580555555556',
'lng':  '-81.4669444444445'},
{'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '28.5413888888889',
'lng':  '-81.3775'},
{'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '28.5413888888889',
'lng':  '-81.3775'},
{'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '28.5413888888889',
'lng':  '-81.3775'},
{'description':  '<b>'  'Company ID: ' '</b>' "Test",
'lat':  '29.2108333333333',
'lng':  '-81.0233333333333'},   
    ];

////////////////////////////////////////////////
    
   oms = new OverlappingMarkerSpiderfier(map,
        {markersWontMove: true, markersWontHide: true, keepSpiderfied: true, circleSpiralSwitchover: 40 });

    var bounds = new google.maps.LatLngBounds();
    var infoWindow = new google.maps.InfoWindow();
    //Set the element ID of you're map's container
    //var map = new google.maps.Map(document.getElementById('map_container'), mapOptions);
  

    //Add all the markers
    for (var i = markers.length - 1; i >= 0; i--) {
        var data = markers[i];
        var thisLatLng = new google.maps.LatLng(data.lat,data.lng);
        //Position current marker
        var marker = new google.maps.Marker({
            position:thisLatLng,
            map:map,
            icon: {url: "https://maps.google.com/mapfiles/ms/icons/blue-dot.png"}
        });
       
        bounds.extend(marker.position);
        (function(marker, data) {
            //Add a click event listener to current marker
            google.maps.event.addListener(marker, "click", function(e){
                //Add description content
                infoWindow.setContent(data.description);
                infoWindow.open(map, marker);
            });
            
            oms.addMarker(marker);

        })(marker, data);
    }


///////////////////////////////////////////////// 
    
  //Autocomplete address search

  // Create the search box and link it to the UI element.
  var input = document.getElementById('searchtext');
  var searchBox = new google.maps.places.SearchBox(input);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });

  var markers = [];
  // Listen for the event fired when the user selects a prediction and retrieve
  // more details for that place.
  searchBox.addListener('places_changed', function() {
    var places = searchBox.getPlaces();

    if (places.length == 0) {
      return;
    }

    // Clear out the old markers.
    markers.forEach(function(marker) {
      marker.setMap(null);
    });
    markers = [];

    // For each place, get the icon, name and location.
    var bounds = new google.maps.LatLngBounds();
    places.forEach(function(place) {
      if (!place.geometry) {
        console.log("Returned place contains no geometry");
        return;
      }
      var icon = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };

      // Create a marker for each place.
      markers.push(new google.maps.Marker({
        map: map,
        animation: google.maps.Animation.DROP,
        title: place.name,
        position: place.geometry.location
      }));

      if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
      } else {
        bounds.extend(place.geometry.location);
      }
      if (circle && circle.setMap) circle.setMap(null);
      var value = $("#range").val();
      circle = new google.maps.Circle({
        center: place.geometry.location,
        radius: value * METERS_PER_MILE,
        map: map
      });
      map.fitBounds(circle.getBounds());
    });
    map.fitBounds(bounds);
  });    
}  
      

window.onload = function() {
    if(!window.location.hash) {
        window.location = window.location   '#loaded';
        window.location.reload();
    }
}    
 
//Line I am having difficulty with on my computer and other computers    
google.maps.event.addDomListener(window, 'load', myMap);
         
  
if(window.location.protocol != 'https:') {
  location.href =   location.href.replace("http://", "https://");
}
  
    </script>
    
</body>

</html>

Google Map Api V3 dont display after hosting change

Uncaught ReferenceError: google is not defined

CodePudding user response:

Maybe remove async from this guy?

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY_HERE&callback=initAutocomplete&libraries=places&v=weekly&channel=2"
      async></script>

CodePudding user response:

Alternatively, keep async and use the callback properly &callback=myMap. You want want to move the <script src="https://maps.googleapis.com to after the script defining myMap though.

  •  Tags:  
  • Related