简体   繁体   中英

Google Maps APIv3 - adding markers via geocode

So I've got this script where I'm trying to add markers to a map I've created with Javascript. I think I'm pretty near to getting it right (yeah, right) but I'm not sure what I'm doing wrong and I can't seem to decipher the error I'm getting.

The first thing I do is add the google API key to my site.

Then, the first thing I do in my script is load the search and maps APIs:

(function ($) {
  $("document").ready(function() {
    google.load("maps", 2, {"callback": mapsLoaded});
  });
})(jQuery);

After the 'maps' API has loaded, the mapsLoaded method gets called:

function mapsLoaded() {
  //Create the options for the map and imediately after create the map.
  var myOptions = {
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("result_map"), myOptions);

  showUserLocation(map);

  var image = '../misc/planbMarker.png';
  var postcodes = document.getElementsByClassName('result-postcode');
  var geocoder = new google.maps.Geocoder();
  for(var i = 0; i < postcodes.length; i++) {
    var address = postcodes[i].value;
    geocoder.geocode({'address': address}, function(results, status){
      if (status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          map: map,
          position: results[i].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}

The function showUserLocation just gets the user's current location and puts it in the map:

function showUserLocation(map) {
  //Define the user's initial location
  var initialLocation;
  //Define the variable to see if geolocation is supported.
  var browserSupportFlag =  new Boolean();
  // Try W3C Geolocation (Preferred)
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  // Browser doesn't support Geolocation
  } else {
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }
  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      alert("Geolocation service failed. Defaulting to Aberdeen.");
      initialLocation = new google.maps.LatLng(57.149953,-2.104053);
    } else {
      alert("Your browser doesn't support geolocation. We've placed you in Aberdeen.");
      initialLocation = new google.maps.LatLng(57.149953,-2.104053);
    }
    map.setCenter(initialLocation);
  }
  //Put a marker on the user's current position different than the markers for the venues.
  navigator.geolocation.getCurrentPosition(function(position) {
    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
    map: map,
    title:"Hello World!"});
  });  
} 

Now, the error I'm getting when I run this is: Uncaught TypeError: Cannot call method 'appendChild' of null at maps:1 followed by: Uncaught TypeError: Object #<Object> has no method '__gjsload__' and after about 5 seconds this also pops up in the javascript console:

Error in event handler for 'undefined': TypeError: Cannot call method 'postMessage' of null
at chrome/RendererExtensionBindings:100:18
at chrome-extension://bmagokdooijbeehmkpknfglimnifench/contentScript.js:128:13
at [object Object].dispatch (chrome/EventBindings:182:28)
at chrome/RendererExtensionBindings:99:24
at [object Object].dispatch (chrome/EventBindings:182:28)
at Object.<anonymous> (chrome/RendererExtensionBindings:149:22)

On a sidenote, and as another possibly symptom, when this error is happening Chrome is displaying a blank page (if you go to view source the markup is all there but the page is blank). I'm running Drupal 7.10.

Does anyone have any ideas on what I'm doing wrong?

Firstly, Google Maps API 3 doesn't require an API key (unless we're referring to the recently introduced key for sites with over 25,000 daily map views which might need to pay for usage). It sounds like you're mixing up the keys required for API 2 with code for API 3.

Secondly, this is all wrong. 'i' is a variable for the postcodes array, it has no relationship to the results array

for(var i = 0; i < postcodes.length; i++) {
    var address = postcodes[i].value;
    geocoder.geocode({'address': address}, function(results, status){
      if (status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          map: map,
          position: results[i].geometry.location

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