Rectangle 27 1

Geocoding the failing zipcode, then reverse geocoding the resulting coordinates look like it will give a set of results that could be used.

The results I get from doing that for your example are:

code snippet (using the Google Maps Javascript API DistanceMatrix Service):

var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
var map;
// https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=47601,%20USA&destinations=02543,%20USA
function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

  service.getDistanceMatrix({
    origins: ["47601, USA"],
    destinations: ["02543, USA"],
    travelMode: 'DRIVING',
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
  }, function(response, status) {
    console.log("status=" + status + ", response=" + response);
    if (status != 'OK') {
      alert('Error was: ' + status);
    } else {
      var originList = response.originAddresses;
      var destinationList = response.destinationAddresses;
      var outputDiv = document.getElementById('output');
      outputDiv.innerHTML = '';

      for (var i = 0; i < originList.length; i++) {
        var results = response.rows[i].elements;
        for (var j = 0; j < results.length; j++) {
          if (results[j].status != 'OK') {
            alert("result[" + j + "] Error was: " + results[j].status);
            geocoder.geocode({
              'address': destinationList[i]
            }, reverseGeocodeResult);
            break;
          }
          outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
            ': ' + results[j].distance.text + ' in ' +
            results[j].duration.text + '<br>';
        }
      }
    }
  });
}

function reverseGeocodeResult(response, status) {
  if (status == 'OK') {
    geocoder.geocode({
      latLng: response[0].geometry.location
    }, findDistancesToResponses);
  }
}

function findDistancesToResponses(response, status) {
  var destArr = [];
  for (var i = 0; i < response.length; i++) {
    destArr.push(response[i].geometry.location);
  }
  service.getDistanceMatrix({
    origins: ["47601, USA"],
    destinations: destArr,
    travelMode: 'DRIVING',
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
  }, function(response, status) {
    var originList = response.originAddresses;
    var destinationList = response.destinationAddresses;
    var outputDiv = document.getElementById('output');
    outputDiv.innerHTML = '';

    for (var i = 0; i < originList.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {
        if (results[j].status != 'OK') {
          alert("result[" + j + "] " + destinationList[j] + " Error was: " + results[j].status);
        }
        outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
          ': ' + results[j].distance.text + ' in ' +
          results[j].duration.text + '<br>';
      }
    }
  })
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<div id="map_canvas"></div>
<div id="output"></div>

Interesting, I'll give this a shot and accept if it takes care of the issue.

google maps - Calculating distance when location is "off road" - Stack...

google-maps google-distancematrix-api
Rectangle 27 2

It is not possible to display traffic only for a route using the Google Maps JavaScript API, as you said, you can show traffic for a city but not singles streets.

How can you display traffic for a route using the Google Maps JavaScri...

javascript google-maps google-maps-api-3
Rectangle 27 1

I understand you would like to generate a draggable route using Google Maps JavaScript API and open the same route in Google Maps website. Once the user dragged the way point and changed the route, you would like to update the website URL and open updated route on Google Maps website. Is it correct?

You can implement this using the following ideas:

I have created a small example that shows this idea. Please have a look, but be aware that this code is not production ready, it's just a proof of concept. Each time the route is changed the link 'Open in Google Maps' is updated. Also note that I used promises, so this code will work only in modern browsers.

var origin = 'Barcelona, Spain';
var destin = 'Madrid, Spain';
var geocoder;
var hashPlaces = {};

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {lat: 41.557922, lng: -0.895386},  //Spain.
    gestureHandling: 'greedy'
  });

  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    panel: document.getElementById('right-panel')
  });
  geocoder = new google.maps.Geocoder();

  directionsDisplay.addListener('directions_changed', function() {
    computeTotalDistance(directionsDisplay.getDirections());
    prepareMapLink(directionsDisplay.getDirections());
  });

  displayRoute(origin, destin, directionsService,
      directionsDisplay);
}

function displayRoute(origin, destination, service, display) {
  service.route({
    origin: origin,
    destination: destination,
    waypoints: [{location: 'Lleida, Spain'}, {location: 'Zaragoza, Spain'}],
    travelMode: 'DRIVING',
    avoidTolls: true
  }, function(response, status) {
    if (status === 'OK') {
      display.setDirections(response);
    } else {
      alert('Could not display directions due to: ' + status);
    }
  });
}

function computeTotalDistance(result) {
  var total = 0;
  var myroute = result.routes[0];
  for (var i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }
  total = total / 1000;
  document.getElementById('total').innerHTML = total + ' km';
}

function geocodePlaceId (placeId) {
  return new Promise(function(resolve, reject) {
      geocoder.geocode({'placeId': placeId}, function(results, status) {
         if (status === 'OK') {
            var r = Object.create(null);
            r[placeId] = results[0].formatted_address
            resolve(r);
         } else {
            reject('Geocode was not successful for the following reason: ' + status);
         }
      });
  });
}

function prepareMapLink(result) {
  var arrWp = [];
  result.geocoded_waypoints.forEach(function (wp) {
      arrWp.push(wp.place_id);
  });

  var oplaceId = arrWp.shift();
  var dplaceId = arrWp.pop();  

  var arrProm = [];
  arrWp.forEach( function (pId) {
    if (!hashPlaces[pId]) {
      arrProm.push(geocodePlaceId(pId));
    }
  });  

  if (arrProm.length) {
      Promise.all(arrProm).then( function (values) {
          values.forEach(function (val) {
             for (key in val) {
                hashPlaces[key] = val[key];
             }
          });
          constructMapsUrl(oplaceId, dplaceId, arrWp);
      }).catch(reason => { 
          console.log(reason)
      });
  } else {
      constructMapsUrl(oplaceId, dplaceId, arrWp);
  }

}

function constructMapsUrl(originId, destinationId, waypoints) {
    var res = "https://www.google.com/maps/dir/?api=1&";
    res += "origin="+encodeURIComponent(origin)+"&origin_place_id="+originId;
    res += "&destination="+encodeURIComponent(destin)+"&destination_place_id="+destinationId;

    var wpAddr = [];
    waypoints.forEach( function (wp) {
        wpAddr.push(hashPlaces[wp]);
    });

    var waypointsStr = encodeURIComponent(wpAddr.join('|'));
    var waypointsIds = waypoints.join('|');

    res += "&waypoints="+waypointsStr+"&waypoint_place_ids="+waypointsIds+"&travelmode=driving";

    var aElem = document.getElementById("mapLink");
    aElem.setAttribute("href", res);
}
#right-panel {
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

#right-panel select, #right-panel input {
  font-size: 15px;
}

#right-panel select {
  width: 100%;
}

#right-panel i {
  font-size: 12px;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
  float: left;
  width: 63%;
  height: 100%;
}
#right-panel {
  float: right;
  width: 34%;
  height: 100%;
}
.panel {
  height: 100%;
  overflow: auto;
}
<div id="map"></div>
<div id="right-panel">
  <p>Total Distance: <span id="total"></span></p>
  <p><a id="mapLink" href="#" title="Open in Google Maps" target="_blank">Open in Google Maps</a></p>
</div>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap"></script>

Thank you very much, you have understood me one for a long time. Yes, I was looking for this answer.

Forgive me for the impudence, I wanted to ask more clarifying question, but I can not post here in the comments because the link is very large from Google maps and exceeds the number of characters allowed. How can I ask you an additional question?

Post a question and leave a link here. I will have a look.

You helped me a lot. But still this problem is not completely solved. ...

javascript - In Google Maps API generate a Google Maps URL - Stack Ove...

javascript google-maps web google-maps-api-3 google-maps-urls
Rectangle 27 1

You can do this using the Google Maps JavaScript API v3. You'll need to get the geolocation (per the link that you have set up). You'll want to use the watchPosition method with the geolocation API.

From there, every time the positon changes, you can make a call to the Maps API and update the map center and/or location of the marker that represents the users current location.

javascript - Add location marker like Google Maps Mobile App onto JS v...

javascript html5 google-maps
Rectangle 27 1

Create random points inside the bounds of the circle:

var bounds = circle.getBounds();
map.fitBounds(bounds);
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();    
for (var i = 0; i < 100; i++) {
   // create a random point inside the bounds
   var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
   var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
   var point = new google.maps.LatLng(ptLat,ptLng);

If they are within the circle itself keep them (add them to the map in this case), otherwise discard them:

if (google.maps.geometry.spherical.computeDistanceBetween(point,circle.getCenter()) < circle.getRadius()) {
     createMarker(map, point,"marker "+i);
     // break;  if only need one point
   } // else nothing.

Example using the Google Maps Javascript API v3:

var circle;
var infowindow = new google.maps.InfoWindow({});

function initialize() {
  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: new google.maps.LatLng(22.7964, 79.8456),
    mapTypeId: google.maps.MapTypeId.HYBRID
  });

  circle = new google.maps.Circle({
    center: map.getCenter(),
    radius: 1000, // meters
    strokeColor: "#0000FF",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#0000FF",
    fillOpacity: 0.26
  });

  circle.setMap(map);

  var bounds = circle.getBounds();
  map.fitBounds(bounds);
  var sw = bounds.getSouthWest();
  var ne = bounds.getNorthEast();
  for (var i = 0; i < 100; i++) {
    var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
    var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
    var point = new google.maps.LatLng(ptLat, ptLng);
    if (google.maps.geometry.spherical.computeDistanceBetween(point, circle.getCenter()) < circle.getRadius()) {
      createMarker(map, point, "marker " + i);
      // break;
    }
  }

}

function createMarker(map, point, content) {
  var marker = new google.maps.Marker({
    position: point,
    map: map
  });
  google.maps.event.addListener(marker, "click", function(evt) {
    infowindow.setContent(content + "<br>" + marker.getPosition().toUrlValue(6));
    infowindow.open(map, marker);
  });
  return marker;
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map" style="width: 530px; height: 500px">
</div>
var sw = bounds.getSouthWest(); var ne = bounds.getNorthEast(); var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat(); var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();

Get a random point inside the bounds.

@geocodezip how does the API detects the southwest bound of a circle? Is it by adding a square with the same radius as the circle as boundary ?

getBounds

php - Random generating coordinates within a circle - Stack Overflow

php google-maps math coordinates
Rectangle 27 5

According the google docs this happened because the url on which you are using the Google Maps API, it not registered in list of allowed referrers

All subdomains of a specified domain are also authorized.

http://www.testdomain.com
http://testdomain.com

In my case it was misconfigured DNS for the domain. For example: www.testdomain.com worked fine testdomain.com didn't work causing an error

It would seem the logic of that is reversed? Unless I am missing something.

Google Maps JavaScript API RefererNotAllowedMapError - Stack Overflow

javascript google-maps google-maps-api-3
Rectangle 27 5

According the google docs this happened because the url on which you are using the Google Maps API, it not registered in list of allowed referrers

All subdomains of a specified domain are also authorized.

http://www.testdomain.com
http://testdomain.com

In my case it was misconfigured DNS for the domain. For example: www.testdomain.com worked fine testdomain.com didn't work causing an error

It would seem the logic of that is reversed? Unless I am missing something.

Google Maps JavaScript API RefererNotAllowedMapError - Stack Overflow

javascript google-maps google-maps-api-3
Rectangle 27 18

Yep, this is definitely possible using the API. You can construct a GDirections object without a map or directions div. You can do a load request from A to B and then call the getDuration method to get the total travel time.

First you need to create a directions object:

// no need to pass map or results div since
// we are only interested in travel time.
var directions = new GDirections ();

Then do your load request to resolve the directions (I have used two latitudes and longitudes as my start and end points, but you can use addresses here as well):

var wp = new Array ();
wp[0] = new GLatLng(32.742149,119.337218);
wp[1] = new GLatLng(32.735347,119.328485);
directions.loadFromWaypoints(wp);

Then you need to listen for the load event so you can call getDuration once the directions have been resolved:

GEvent.addListener(directions, "load", function() {
    $('log').innerHTML = directions.getDuration ().seconds + " seconds";
        });

You can find the whole example here and the JavaScript here. You can check the Google Maps Documentation for more info about the options you can give the GDirections object (like walking distance etc...). You should also listen to the error event for geocoding failures.

now let's say I have a kml file with 50 points in it. I'd like to get the travel times between all these point, what do you recommend I should do?

The link does not work anymore!

This appears to yield the driving time under ideal traffic conditions (ignoring current conditions). The results are identical regardless of departure time.

the whole example is dead - perhaps changes in the api?

Using Google Maps API to get travel time data - Stack Overflow

api google-maps
Rectangle 27 17

Yep, this is definitely possible using the API. You can construct a GDirections object without a map or directions div. You can do a load request from A to B and then call the getDuration method to get the total travel time.

First you need to create a directions object:

// no need to pass map or results div since
// we are only interested in travel time.
var directions = new GDirections ();

Then do your load request to resolve the directions (I have used two latitudes and longitudes as my start and end points, but you can use addresses here as well):

var wp = new Array ();
wp[0] = new GLatLng(32.742149,119.337218);
wp[1] = new GLatLng(32.735347,119.328485);
directions.loadFromWaypoints(wp);

Then you need to listen for the load event so you can call getDuration once the directions have been resolved:

GEvent.addListener(directions, "load", function() {
    $('log').innerHTML = directions.getDuration ().seconds + " seconds";
        });

You can find the whole example here and the JavaScript here. You can check the Google Maps Documentation for more info about the options you can give the GDirections object (like walking distance etc...). You should also listen to the error event for geocoding failures.

now let's say I have a kml file with 50 points in it. I'd like to get the travel times between all these point, what do you recommend I should do?

The link does not work anymore!

This appears to yield the driving time under ideal traffic conditions (ignoring current conditions). The results are identical regardless of departure time.

the whole example is dead - perhaps changes in the api?

Using Google Maps API to get travel time data - Stack Overflow

api google-maps
Rectangle 27 17

What you want is the Distance Matrix API. That is, if you are really using it in combination google maps. Note that Google prohibits the use of this API if you are not using it with a Google Map somewhere on the page.

Here's a basic example of the Distance Matrix API:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var origin = new google.maps.LatLng(55.930385, -3.118425),
    destination = "Stockholm, Sweden",
    service = new google.maps.DistanceMatrixService();

service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false
    }, 
    callback
);

function callback(response, status) {
    var orig = document.getElementById("orig"),
        dest = document.getElementById("dest"),
        dist = document.getElementById("dist");

    if(status=="OK") {
        orig.value = response.destinationAddresses[0];
        dest.value = response.originAddresses[0];
        dist.value = response.rows[0].elements[0].distance.text;
    } else {
        alert("Error: " + status);
    }
}
</script>
</head>
<body>
    <br>
    Basic example for using the Distance Matrix.<br><br>
    Origin: <input id="orig" type="text" style="width:35em"><br><br>
    Destination: <input id="dest" type="text" style="width:35em"><br><br>
    Distance: <input id="dist" type="text" style="width:35em">
</body>
</html>

This is a version of google's example adapted to your personal taste which I found in the Google Maps Api v3 - Distance Matrix section

This works if you make the following update: origins: [origin], destinations: [destination],

@Michael, good eye, thanks for the correction. And for any interested parties, here's a fiddle with the corrections while I'm at it.

How can I pass multiple destinations?

javascript - How to calculate distance between two cities using google...

javascript google-maps distance
Rectangle 27 16

For the record: At this time (year 2015) GDirections, GLatLng, GEvent, etc. are deprecated.

In the following snippet, location and target are objects containing latitude and longitude coordinates.

1) The google.maps.DirectionsService class admit both LatLng and string values to feed their origin and destination properties. 2) A LatLng is a point in geographical coordinates: latitude and longitude.

var origin = new google.maps.LatLng( location.latitude, location.longitude ); // using google.maps.LatLng class
var destination = target.latitude + ', ' + target.longitude; // using string

var directionsService = new google.maps.DirectionsService();
var request = {
    origin: origin, // LatLng|string
    destination: destination, // LatLng|string
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route( request, function( response, status ) {

    if ( status === 'OK' ) {
        var point = response.routes[ 0 ].legs[ 0 ];
        $( '#travel_data' ).html( 'Estimated travel time: ' + point.duration.text + ' (' + point.distance.text + ')' );
    }
} );

Using Google Maps API to get travel time data - Stack Overflow

api google-maps
Rectangle 27 16

For the record: At this time (year 2015) GDirections, GLatLng, GEvent, etc. are deprecated.

In the following snippet, location and target are objects containing latitude and longitude coordinates.

1) The google.maps.DirectionsService class admit both LatLng and string values to feed their origin and destination properties. 2) A LatLng is a point in geographical coordinates: latitude and longitude.

var origin = new google.maps.LatLng( location.latitude, location.longitude ); // using google.maps.LatLng class
var destination = target.latitude + ', ' + target.longitude; // using string

var directionsService = new google.maps.DirectionsService();
var request = {
    origin: origin, // LatLng|string
    destination: destination, // LatLng|string
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route( request, function( response, status ) {

    if ( status === 'OK' ) {
        var point = response.routes[ 0 ].legs[ 0 ];
        $( '#travel_data' ).html( 'Estimated travel time: ' + point.duration.text + ' (' + point.distance.text + ')' );
    }
} );

Using Google Maps API to get travel time data - Stack Overflow

api google-maps
Rectangle 27 8

Are you using JS API V3? From Google Maps Docs: "Note: This version of the Google Maps JavaScript API no longer needs API keys!"

I am using jQuery Mobile and Google Maps, ran into problems regarding map_canvas div height and related settings. What exact problem are you seeing, no map or map in wrong place? Does firebug show anything amiss?

I've had great success with mobile examples here . I don't use a key even though some of these examples do.

android - Google maps are not displayed on device with using jquerymob...

android google-maps cordova jquery-mobile store
Rectangle 27 1

If you use the Google Maps Javascript API v3 (as opposed to the Fusion Tables API you are currently using) you can set the 'radius' property of your heatmap object to do exactly what you're attempting to do.

Unfortunately, there is no way to do this using the Fusion Tables API. The documentation even mentions this explicitly:

javascript - Configuring heatmap overlays using Google Maps API - Stac...

javascript google-maps-api-3 overlay google-fusion-tables heatmap
Rectangle 27 2

If your using Google Maps v3

The javascript include for the google maps api has changed:

Google Maps API - undefined ROADMAP property? - Stack Overflow

google-maps google-maps-api-3
Rectangle 27 3

updated: here is an example of using the google clientlocation api and localsearch using jsonp.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAALDWeTDQHOJCbCf0JnUqL8BT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQA7AE8xB9MyWgHECPY2qimOp7BUQ"></script>

    <script src="scripts/clientLocation.js" type="text/javascript"></script>

    <script src="scripts/localSearch.js" type="text/javascript"></script>

    <script type="text/javascript">



        function $g(id) {
            return document.getElementById(id);
        }

        function displayLocation(latitudeEl, longitudeEl, cityEl, regionEl, countryEl, country_codeEl) {
            var cloc = new ClientLocation.Location(google.loader.ClientLocation);
            if (latitudeEl) latitudeEl.innerHTML = cloc.latitude;
            if (longitudeEl) longitudeEl.innerHTML = cloc.longitude;
            if (cityEl) cityEl.innerHTML = cloc.address.city;
            if (regionEl) regionEl.innerHTML = cloc.address.region;
            if (country) country.innerHTML = cloc.address.country;
            if (country_codeEl) country_codeEl.innerHTML = cloc.address.country_code;
        }
        function localSearch(term, callback, context) {
            var cloc = new ClientLocation.Location(google.loader.ClientLocation);
            var searchUrl = 'http://www.google.com/uds/GlocalSearch?callback=' + callback + '&context=' + context + '&hl=en&q=' + encodeURIComponent(term) + '&sll=' + cloc.latitude + ',' + cloc.longitude + '&key=ABQIAAAALDWeTDQHOJCbCf0JnUqL8BT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQA7AE8xB9MyWgHECPY2qimOp7BUQ&v=1.0';

            // http://jaybyjayfresh.com/2007/09/17/using-script-tags-to-do-remote-http-calls-in-javascript/
            scriptLoaded = function() {
                removeNode(newScript);
            };

            var headID = document.getElementsByTagName("head")[0];
            var newScript = document.createElement('script');
            newScript.type = 'text/javascript';
            newScript.onload = scriptLoaded;
            newScript.src = searchUrl;
            headID.appendChild(newScript);
        }
        function search() {
            var term = $g("txtSearch").value;
            localSearch(term, "displayResults", "0");

        }
        function displayResults(context, results, status, details, unused) {
            var titles = [];
            for (var i = 0; i < results.results.length; i++) {
                // this cast is not necessary, just here to illustrate
                // vs intellisense and reduce coding errors.
                var result = new LocalSearch.Result(results.results[i]);
                titles.push(result.title);
            }
            $g("searchResults").innerHTML = titles.join("</br>");
        }
        function init() {

            displayLocation($g("latitude"), $g("longitude"), $g("city"), $g("region"), $g("country"), $g("country_code"));
        }
    </script>

</head>
<body onload="init()">
    <form id="form1" runat="server">
    <div>
        latitude : <span id="latitude"></span>
        <br />
        longitude : <span id="longitude"></span>
        <br />
        city : <span id="city"></span>
        <br />
        region : <span id="region"></span>
        <br />
        country : <span id="country"></span>
        <br />
        country_code : <span id="country_code"></span>
        <br />
    </div>
    <input type="text" id="txtSearch" /><input type="button" id="btnSearch" value="get results"
        onclick="search();" /><br />
    &nbsp;<div id="searchResults">
    </div>
    </form>
</body>
</html>
// <copyright file="clientLocation.js" company="Sky Sanders">
// This source is placed in the Public Domain.
// http://skysanders.net/subtext
// Attribution is appreciated.
// </copyright>


/*
object literal format for google.loader.clientlocation  
{
"latitude": 33.324,
"longitude": -111.867,
"address": {
"city": "Chandler",
"region": "AZ",
"country": "USA",
"country_code": "US"
}
}
*/

var ClientLocation = {};

ClientLocation.Address = function() {
    /// <field name="city" type="String" />
    /// <field name="region" type="String" />
    /// <field name="country" type="String" />
    /// <field name="country_code" type="String" />
    /// <returns type="ClientLocation.Address"/>
    if (arguments.length > 0) {
        this.city = arguments[0].city;
        this.region = arguments[0].region;
        this.country = arguments[0].country;
        this.country_code = arguments[0].country_code;
        return;
    }
    else {
        this.city = "";
        this.region = "";
        this.country = "";
        this.country_code = "";
    }

}
ClientLocation.Location = function() {
    /// <field name="latitude" type="Number" />
    /// <field name="longitude" type="Number" />
    /// <field name="address" type="ClientLocation.Address" />
    if (arguments.length > 0) {

        this.latitude = arguments[0].latitude;
        this.longitude = arguments[0].longitude;
        this.address = arguments[0].address;

    }
    else {
        this.latitude = 0;
        this.longitude = 0;
        this.address = undefined;
    }

}


// <copyright file="localSearc.js" company="Sky Sanders">
// This source is placed in the Public Domain.
// http://skysanders.net/subtext
// Attribution is appreciated.
// </copyright>
/*
GlocalSearch result

{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "computed",
"listingType": "local",
"lat": "33.389689",
"lng": "-111.853909",
"accuracy": "8",
"title": "Best \u003cb\u003eBuy\u003c/b\u003e",
"titleNoFormatting": "Best Buy",
"ddUrl": "http://www.google.com/maps....",
"ddUrlToHere": "http://www.google.com/maps?....",
"ddUrlFromHere": "http://www.google.com/maps?....",
"streetAddress": "1337 South Alma School Road",
"city": "Mesa",
"region": "AZ",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?....",
"url": "http://www.google.com/maps/place?source....",
"content": "",
"maxAge": 604800,
"phoneNumbers": [{
"type": "",
"number": "(480) 644-7139"
},
{
"type": "",
"number": "(480) 464-0444"
}],
"addressLines": ["1337 South Alma School Road", "Mesa, AZ"]
}

*/


var LocalSearch = {};

LocalSearch.PhoneNumber = function() {
    /// <field name="type" type="String"/>
    /// <field name="number" type="String"/>
    /// <returns type="LocalSearch.PhoneNumber"/>

    if (arguments.length > 0) {
        this.type = arguments[0].type;
        this.number = arguments[0].number;
    }
    else {
        this.type = "";
        this.number = "";
    }
}



LocalSearch.Result = function() {
    /// <field name="GsearchResultClass" type="String"/>
    /// <field name="viewportmode" type="String"/>
    /// <field name="listingType" type="String"/>
    /// <field name="lat" type="String"/>
    /// <field name="lng" type="String"/>
    /// <field name="accuracy" type="String"/>
    /// <field name="title" type="String"/>
    /// <field name="titleNoFormatting" type="String"/>
    /// <field name="ddUrl" type="String"/>
    /// <field name="ddUrlToHere" type="String"/>
    /// <field name="ddUrlFromHere" type="String"/>
    /// <field name="streetAddress" type="String"/>
    /// <field name="city" type="String"/>
    /// <field name="region" type="String"/>
    /// <field name="country" type="String"/>
    /// <field name="staticMapUrl" type="String"/>
    /// <field name="url" type="String"/>
    /// <field name="content" type="String"/>
    /// <field name="maxAge" type="Number"/>
    /// <field name="phoneNumbers" type="Array"/>
    /// <field name="addressLines" type="Array"/>
    // <returns type="LocalSearch.Result"/>
    if (arguments.length > 0) {
        this.GsearchResultClass = arguments[0].GsearchResultClass;
        this.viewportmode = arguments[0].viewportmode;
        this.listingType = arguments[0].listingType;
        this.lat = arguments[0].lat;
        this.lng = arguments[0].lng;
        this.accuracy = arguments[0].accuracy;
        this.title = arguments[0].title;
        this.titleNoFormatting = arguments[0].titleNoFormatting;
        this.ddUrl = arguments[0].ddUrl;
        this.ddUrlToHere = arguments[0].ddUrlToHere;
        this.ddUrlFromHere = arguments[0].ddUrlFromHere;
        this.streetAddress = arguments[0].streetAddress;
        this.city = arguments[0].city;
        this.region = arguments[0].region;
        this.country = arguments[0].country;
        this.staticMapUrl = arguments[0].staticMapUrl;
        this.url = arguments[0].url;
        this.content = arguments[0].content;
        this.maxAge = arguments[0].maxAge;
        this.phoneNumbers = arguments[0].phoneNumbers;
        this.addressLines = arguments[0].addressLines;

    }
    else {

        this.GsearchResultClass = "";
        this.viewportmode = "";
        this.listingType = "";
        this.lat = "";
        this.lng = "";
        this.accuracy = "";
        this.title = "";
        this.titleNoFormatting = "";
        this.ddUrl = "";
        this.ddUrlToHere = "";
        this.ddUrlFromHere = "";
        this.streetAddress = "";
        this.city = "";
        this.region = "";
        this.country = "";
        this.staticMapUrl = "";
        this.url = "";
        this.content = "";
        this.maxAge = 0;
        this.phoneNumbers = [];
        this.addressLines = [];
    }


}

Thanks for the example code Sanders I was basically looking for a way where the user specifies the business name and city - and using that info I can pull the address using Google code. Roland provided me with this link which does exactly that: code.google.com/apis/ajax/playground/#center_localsearch But my concern is whether I can use that information and store it in my database

yeah, i was just finishing up a sample of pulling from GLocalSearch with a simple JsonP strategy. As for storage, and usage of this sample, you will have to examine the terms of use posted on the google api page. I posted the sample for other people who come looking for this type of thing

You need to check the Google license. I do not believe you can "scrub" their data for re-use / storage. For our map plotting we had to go the business license with them. Plus you are limited on the number of calls you can make on the free versions, but that may not impact you.

Using Google Maps API to get Address of Business - Stack Overflow

google-maps google-maps-api-3
Rectangle 27 72

This happens because the fitBounds() needs to snap to a viewport that fits the map canvas using the maximum zoom level possible. On the other hand, the viewport returned by the geocoder is not dependent on the size, layout or zoom level of the map canvas. Therefore the fitBounds() method adjusts the map's viewport in order to view the passed LatLngBounds in full at the centre of the map.

You may want to check the following example for a clearer demonstation:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps fitBounds Demo</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 500px; height: 350px"></div> 

   <script type="text/javascript"> 
      var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP };
      var map = new google.maps.Map(document.getElementById("map"), myOptions);
      var geocoder = new google.maps.Geocoder();

      geocoder.geocode({'address': 'RU'}, function (results, status) {
         var ne = results[0].geometry.viewport.getNorthEast();
         var sw = results[0].geometry.viewport.getSouthWest();

         map.fitBounds(results[0].geometry.viewport);               

         var boundingBoxPoints = [
            ne, new google.maps.LatLng(ne.lat(), sw.lng()),
            sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
         ];

         var boundingBox = new google.maps.Polyline({
            path: boundingBoxPoints,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 2
         });

         boundingBox.setMap(map);
      }); 
   </script> 
</body> 
</html>

Below are some screenshots for various countries from the above example. The red bounding box is the viewport returned by the geocoder. Note the difference between the bounding box and the actual viewport, as adjusted by fitBounds():

Thanks a lot for the thorough explanation. The boundingBox was a great idea to make this clear.

Just to clarfiy, it's a matter of aspect ratio. This took me quite a while to figure out. In the three example images above, the aspect ratio of each country's bounding box is different, but the overall map bounding box aspect ratio remains the same. As analogy, not all sizes wear the same size pair of pants, but pants come in set sizes, hence, some people have a harder time finding a good fit. Not all countries fit nicely in the Google bounding box at a particular zoom.

javascript - fitbounds() in Google maps api V3 does not fit bounds - S...

javascript google-maps google-maps-api-3 fitbounds
Rectangle 27 72

This happens because the fitBounds() needs to snap to a viewport that fits the map canvas using the maximum zoom level possible. On the other hand, the viewport returned by the geocoder is not dependent on the size, layout or zoom level of the map canvas. Therefore the fitBounds() method adjusts the map's viewport in order to view the passed LatLngBounds in full at the centre of the map.

You may want to check the following example for a clearer demonstation:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps fitBounds Demo</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 500px; height: 350px"></div> 

   <script type="text/javascript"> 
      var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP };
      var map = new google.maps.Map(document.getElementById("map"), myOptions);
      var geocoder = new google.maps.Geocoder();

      geocoder.geocode({'address': 'RU'}, function (results, status) {
         var ne = results[0].geometry.viewport.getNorthEast();
         var sw = results[0].geometry.viewport.getSouthWest();

         map.fitBounds(results[0].geometry.viewport);               

         var boundingBoxPoints = [
            ne, new google.maps.LatLng(ne.lat(), sw.lng()),
            sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
         ];

         var boundingBox = new google.maps.Polyline({
            path: boundingBoxPoints,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 2
         });

         boundingBox.setMap(map);
      }); 
   </script> 
</body> 
</html>

Below are some screenshots for various countries from the above example. The red bounding box is the viewport returned by the geocoder. Note the difference between the bounding box and the actual viewport, as adjusted by fitBounds():

Thanks a lot for the thorough explanation. The boundingBox was a great idea to make this clear.

Just to clarfiy, it's a matter of aspect ratio. This took me quite a while to figure out. In the three example images above, the aspect ratio of each country's bounding box is different, but the overall map bounding box aspect ratio remains the same. As analogy, not all sizes wear the same size pair of pants, but pants come in set sizes, hence, some people have a harder time finding a good fit. Not all countries fit nicely in the Google bounding box at a particular zoom.

javascript - fitbounds() in Google maps api V3 does not fit bounds - S...

javascript google-maps google-maps-api-3 fitbounds
Rectangle 27 72

This happens because the fitBounds() needs to snap to a viewport that fits the map canvas using the maximum zoom level possible. On the other hand, the viewport returned by the geocoder is not dependent on the size, layout or zoom level of the map canvas. Therefore the fitBounds() method adjusts the map's viewport in order to view the passed LatLngBounds in full at the centre of the map.

You may want to check the following example for a clearer demonstation:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps fitBounds Demo</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 500px; height: 350px"></div> 

   <script type="text/javascript"> 
      var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP };
      var map = new google.maps.Map(document.getElementById("map"), myOptions);
      var geocoder = new google.maps.Geocoder();

      geocoder.geocode({'address': 'RU'}, function (results, status) {
         var ne = results[0].geometry.viewport.getNorthEast();
         var sw = results[0].geometry.viewport.getSouthWest();

         map.fitBounds(results[0].geometry.viewport);               

         var boundingBoxPoints = [
            ne, new google.maps.LatLng(ne.lat(), sw.lng()),
            sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
         ];

         var boundingBox = new google.maps.Polyline({
            path: boundingBoxPoints,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 2
         });

         boundingBox.setMap(map);
      }); 
   </script> 
</body> 
</html>

Below are some screenshots for various countries from the above example. The red bounding box is the viewport returned by the geocoder. Note the difference between the bounding box and the actual viewport, as adjusted by fitBounds():

Thanks a lot for the thorough explanation. The boundingBox was a great idea to make this clear.

Just to clarfiy, it's a matter of aspect ratio. This took me quite a while to figure out. In the three example images above, the aspect ratio of each country's bounding box is different, but the overall map bounding box aspect ratio remains the same. As analogy, not all sizes wear the same size pair of pants, but pants come in set sizes, hence, some people have a harder time finding a good fit. Not all countries fit nicely in the Google bounding box at a particular zoom.

javascript - fitbounds() in Google maps api V3 does not fit bounds - S...

javascript google-maps google-maps-api-3 fitbounds
Rectangle 27 76

Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.

BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.

<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>

This should be marked as the correct answer for this question. Seems silly that someone would ask why the API key says it's missing if they never placed it there to begin with.

Great! But which is the direct link to generate the API Key? Thanks!

i have the same issue, but i don't know how to add this key, what is the nature of the key and how to choose it.

the key is a string you get on the site linked in my answer. You add it to the api load url as a GET var. see above

Google Maps API warning: NoApiKeys - Stack Overflow

google-maps google-maps-api-3