Rectangle 27 8

You need to use different API for that. First of all, don't use JS but PHP, here's the code snippet that should work for you ;)

$from = "Wickowskiego 72, d";
$to = "Gazowa 1, d";

$from = urlencode($from);
$to = urlencode($to);

$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);

$time = 0;
$distance = 0;

foreach($data->rows[0]->elements as $road) {
    $time += $road->duration->value;
    $distance += $road->distance->value;
}

echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
echo "Time: ".$time." seconds";
echo "<br/>";
echo "Distance: ".$distance." meters";
To: Gazowa 1, 91-076 d, Poland
From: Wickowskiego 72, d, Poland
Time: 206 seconds
Distance: 1488 meters

Dear Michal,This is just what I need. Thanks a lot. I have brought the time to hour and distance to km, but the only thing I need to know is how to round it. But I work it out. Thanks so much an all on the second christmas day!!!

Got it! It was the round() function :-) Thank you again so much. It saves a lot of time.

Distance from point A to B using Google Maps, PHP and MySQL - Stack Ov...

php google-maps-api-3 distance
Rectangle 27 2

I've written a code snippet that allows you to retrieve all nearby cities by combining the Google Maps Geocoding API and GeoNames.org API (besides a file_get_contents your could also do a cURL request).

/*
 * Get cities based on city name and radius in KM
 */

// get geocode object as array from The Google Maps Geocoding API
$geocodeObject = json_decode(file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address={CITY NAME},{COUNTRY CODE}'), true);

// get latitude and longitude from geocode object
$latitude = $geocodeObject['results'][0]['geometry']['location']['lat'];
$longitude = $geocodeObject['results'][0]['geometry']['location']['lng'];

// set request options
$responseStyle = 'short'; // the length of the response
$citySize = 'cities15000'; // the minimal number of citizens a city must have
$radius = 30; // the radius in KM
$maxRows = 30; // the maximum number of rows to retrieve
$username = '{YOUR USERNAME}'; // the username of your GeoNames account

// get nearby cities based on range as array from The GeoNames API
$nearbyCities = json_decode(file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat='.$latitude.'&lng='.$longitude.'&style='.$responseStyle.'&cities='.$citySize.'&radius='.$radius.'&maxRows='.$maxRows.'&username='.$username, true));

// foreach nearby city get city details
foreach($nearbyCities->geonames as $cityDetails)
{
    // do something per nearby city
}

be carefull with your requests amount because the API's are limited

For more information about the API's visit the following url's:

php - Can I use Google API for finding nearest cities? - Stack Overflo...

php google-maps google-geocoding-api
Rectangle 27 2

You really need to loop and do multiple checks of what google found at these points a small script to actually reads/loop the returned data would be (in PHP):

Now based on the documentation:

Note that the reverse geocoder returned more than one result. ...etc

Generally, addresses are returned from most specific to least specific; the more exact address is the most prominent result...etc

You only need the first result to get what you want (or at least to search for it there $data->results[0]->. So have a read of the types and based on that you can check if the result you want present or not:

<?php
$data = json_decode(file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=46.1124,1.245&sensor=true"));
if($data->status == "OK") {
    if(count($data->results)) {
        foreach($data->results[0]->address_components as $component) {
            if(in_array("premise",$component->types) || in_array("route",$component->types) || in_array("park",$component->types)) {
                echo $component->long_name . "<br />";
            }
        }
    }
} else {
    // error
}
?>

just wondering why this was a PHP solution and not a JS solution?

javascript - Reverse Geocoding with Google Map API - Stack Overflow

javascript google-maps geolocation reverse-geocoding
Rectangle 27 1

I have a url like this, that search something in a location:

I need a list of the first 2 results like (Dentist Mr.Example1,Dentist Ex.2).

$searchTerm = 'dentist+austin+texas';

$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $searchTerm;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);

$array = json_decode($response, true);

// var_dump($array);

// Output

$array = $array['results'];

foreach($array as $index => $component)
{
    echo '#' . $index . ' ' . $component['formatted_address'] . '<br>';

    // show only the first 2 items (#0 & #1)
    if($index === 1) {
        break;
    }
}
  • Your search term is "dentist Austin textas" and that becomes 'dentist+austin+texas' when it's part of an URL.
  • The searchTerm is attached to the API URL.
  • This is turned into an $array by setting the second paramter of json_decode() to true.
  • For the display part: that's a simply array iteration. You can get rid of the top-level 'results' array by re-assigning the values to $array.
  • The output is a numbered list of dentists

The initial question was to list the first to results for dentists in austin,tx using the Google Maps API.

This additional requirement changes the API / webservice to use, in order to retrieve rich data. You want more details about the addresses. The data elements "phone_number" and "rating" are part of the Google Places Webservice (Place Details). You need to add your key to the request URLs (&key=API_KEY) in order to access this service.

1) From the first request you extract the "place_id"s.

2) With subsequent requests you retrieve the details about each place via the "Place Details" webservice.

Example: here i'm using the placeid for the first entry:

<?php

// Google GeoCode API
$address = 'dentist+austin+texas';

$array = getGoogleGeoCode($address);
$array = $array['results'];

//var_dump($array);

foreach($array as $index => $component)
{
    echo '#' . $index . ' ' . $component['formatted_address'] . ', ' ;

    // subsequent request for "Place Details"
    $details = getGooglePlaceDetails($component['place_id']);
    $details = $details['result'];
    //var_dump($details);

    echo 'Phone: ' . $details['formatted_phone_number']. ', ' ;

    // rating contains the place's rating, from 1.0 to 5.0, based on aggregated user reviews.
    if(isset($details['rating'])) {
        echo 'Rating: ' . $details['rating'];
    }

    // show only the first two entries
    /*if($index === 1) {
        break;
    }*/

    echo '<br>';
}

function getGooglePlaceDetails($placeid)
{
    // your google API key
    $key = 'AIzaSyCj9yH5x6_5_Om8ebAO2pBlaqJZB-TIViY';
    $url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=' . $placeid . '&key=' . $key;

    return curlRequest($url);
}

function getGoogleGeoCode($address)
{
    $url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address;

    return curlRequest($url);
}

function curlRequest($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}
  • The array element rating is not always present, because it's review based. Just use var_dump($details); to see what is there and pick what you need.
  • To reduce the list, remove the comments around the break statement.

This is almost perfect, but I would like to get also the phone number and the ranking (stars for reviews).

I've updated my answer to include the "Place Details" requests. You might also use a radarSearch of the places API to reduce the number of requests. The details element rating is not always present (review based), just use var_dump($details); to see what is there and pick what you need.

How to get results names from Google Maps Api Search in PHP - Stack Ov...

php google-maps
Rectangle 27 5

I finally found a solution that I'm satisfied with. I'm not going to paste every step because it's going to take like thousand lines but here's it in a nutshell: 1. Parse this field from Google directions api json(https://developers.google.com/maps/documentation/directions/#JSON): "overview_polyline": { 2. Decode the polyline to latitude and longitude points with this: http://unitstep.net/blog/2008/08/02/decoding-google-maps-encoded-polylines-using-php/ 3. Download this https://github.com/bazo/route-boxer. I piled all the code from GeoTools php-files to a one file but that's not propably necessary if you'll know how to use that :) 4. And here is an example of getting those boxes using those scripts:

...

$from = "(Startup point for example: "Turku,Finland")";
$to = "(Destination point fro example: "Porvoo,Finland")";

$json_string = file_get_contents("http://maps.googleapis.com/maps/api/directions/json?origin=$from&destination=$to&sensor=false");
$parsed_json = json_decode($json_string, true);

$polyline = $parsed_json['routes'][0]['overview_polyline']['points'];

$routepoints = decodePolylineToArray($polyline);

$collection = new LatLngCollection($routepoints);

$boxer = new RouteBoxer();

//calculate boxes with 10km distance from the line between points
$boxes = $boxer->box($collection, $distance = 10);

foreach($boxes as $row){

$southWestLtd = $row->southWest->latitude;
$southWestLng = $row->southWest->longitude;
$northEastLtd = $row->northEast->latitude;
$northEastLng = $row->northEast->longitude;

$query = "SELECT * FROM markers WHERE Latitude > $southWestLtd AND Latitude < $northEastLtd AND Longitude > $southEastLng AND Longitude < $norhtEastLng";

}

Run that query and it'll give you only the markers (or what ever you are querying) that are inside those boxes. If you'll need some more detailed instructions just leave a comment. I'm more than happy to help since I spent many nights trying to find a reasonable solution to this.

This will make one SQL query for each polygon routeboxer finds which can be very slow. Why don't you do a SQL query for the route bounding box (rectangle), that you can obtain from Google Maps JSON too and then for every point returned check if the point seats inside one of the polygons of your route?

php - Routeboxer server side - Stack Overflow

php android mysql google-maps
Rectangle 27 5

<?php

/* 
* Given longitude and latitude in North America, return the address using The Google Geocoding API V3
*
*/

function Get_Address_From_Google_Maps($lat, $lon) {

$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";

// Make the HTTP request
$data = @file_get_contents($url);
// Parse the json response
$jsondata = json_decode($data,true);

// If the json data is invalid, return empty array
if (!check_status($jsondata))   return array();

$address = array(
    'country' => google_getCountry($jsondata),
    'province' => google_getProvince($jsondata),
    'city' => google_getCity($jsondata),
    'street' => google_getStreet($jsondata),
    'postal_code' => google_getPostalCode($jsondata),
    'country_code' => google_getCountryCode($jsondata),
    'formatted_address' => google_getAddress($jsondata),
);

return $address;
}

/* 
* Check if the json data from Google Geo is valid 
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
* Given Google Geocode json, return the value in the specified element of the array
*/

function google_getCountry($jsondata) {
    return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"]);
}
function google_getProvince($jsondata) {
    return Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
}
function google_getCity($jsondata) {
    return Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
}
function google_getStreet($jsondata) {
    return Find_Long_Name_Given_Type("street_number", $jsondata["results"][0]["address_components"]) . ' ' . Find_Long_Name_Given_Type("route", $jsondata["results"][0]["address_components"]);
}
function google_getPostalCode($jsondata) {
    return Find_Long_Name_Given_Type("postal_code", $jsondata["results"][0]["address_components"]);
}
function google_getCountryCode($jsondata) {
    return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"], true);
}
function google_getAddress($jsondata) {
    return $jsondata["results"][0]["formatted_address"];
}

/*
* Searching in Google Geo json, return the long name given the type. 
* (If short_name is true, return short name)
*/

function Find_Long_Name_Given_Type($type, $array, $short_name = false) {
    foreach( $array as $value) {
        if (in_array($type, $value["types"])) {
            if ($short_name)    
                return $value["short_name"];
            return $value["long_name"];
        }
    }
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

Feel free to look at my blog for a sample code of how using the code above and sample result.

geolocation - PHP Latitude Longitude to Address - Stack Overflow

php geolocation location latitude-longitude
Rectangle 27 3

Luckily, there is one site I have found where you can get great info on neighborhood boundaries in GeoJson format. Ever heard of "the-neighborhoods-project"? It's here http://zetashapes.com/editor/36061 where I did a search for "Manhattan" and found that page. They have many other cities neighborhoods too. As you will notice, there is a button there to download the GeoJson data as a .json file. Now, I feel it's our responsibility as webmasters & developers to ensure the user need not download more data than necessary, as well as reduce our bandwidth requirements, and I find GeoJson to be bloated and overly large for what we need to get from it. So, first thing is to create a .php file on your server or localhost and name it 'reduce.php' or whatever you want, and fill it with the following php code:

<?php
$jsonString = file_get_contents('36061.json');
$obj = json_decode($jsonString);
$arr = array();
foreach($obj->features as $feature) {
    echo $feature->properties->label.'<br>';//just to let you see all the neighborhood names
    array_push($arr, array($feature->properties->label, $feature->geometry->coordinates));
}
file_put_contents('36061_minimal.json', json_encode($arr));
?>

Then place the '36061.json' file in same directory as the above php file and then run the php file by viewing in browser, and it will create a '36061_minimal.json' file which will be about half the size. O.k, now that that's taken care of, for the example which follows below you will need the following javascript file, in which there is a NeighborhoodGroup constructor that is used to keep track of our different neighborhoods. The most important things to know about it are you should instantiate a new instance of NeighborhoodGroup, and then you add neighborhoods to it by calling it's addNeighborhood(name, polygon) method which you feed a name and a google.maps.Polygon instance, then you can add marker objects to your neighborhood group by calling the addMarker(marker) method & feeding it a google.maps.Marker object, and the marker will be delegated to the appropriate neighborhood if possible or else addMarker will return false if the marker does not fit in any of our neighborhoods. So, name the following file "NeighborhoodGroup.js":

//NeighborhoodGroup.js
//requires that the google maps geometry library be loaded
//via a "libraries=geometry" parameter on the url to the google maps script

function NeighborhoodGroup(name) {
    this.name = name;
    this.hoods = [];
     //enables toggling markers on/off between different neighborhoods if set to true
    this.toggleBetweenHoods = false;
     //enables panning and zooming to fit the particular neighborhood in the viewport
    this.fitHoodInViewport = true;
    this.selectedHood = null;
    this.lastSelectedHood = null;
}

NeighborhoodGroup.prototype.getHood = function (name) {
    for (var i = 0, len = this.hoods.length; i < len; i++) {
        if (this.hoods[i].name == name) {
            return this.hoods[i];
        }
    }
    return null;
};

NeighborhoodGroup.prototype.addNeighborhood = function (name, polygon) {
    var O = this,
        hood = new Neighborhood(name, polygon);
    O.hoods.push(hood);
    google.maps.event.addListener(polygon, 'click', function () {
        if (O.toggleBetweenHoods) {
            O.lastSelectedHood = O.selectedHood;
            O.selectedHood = hood;
            if (O.lastSelectedHood !== null && O.lastSelectedHood.name != name) {
                O.lastSelectedHood.setMarkersVisible(false);
            }
        }
        hood.setMarkersVisible(!hood.markersVisible);
        if (O.fitHoodInViewport) {
            hood.zoomTo();
        }
    });
};

//marker must be a google.maps.Marker object
//addMarker will return true if the marker fits within one
//of this NeighborhoodGroup object's neighborhoods, and
//false if the marker does not fit any of our neighborhoods
NeighborhoodGroup.prototype.addMarker = function (marker) {
    var bool,
        i = 0,
        len = this.hoods.length;
    for (; i < len; i++) {
        bool = this.hoods[i].addMarker(marker);
        if (bool) {
            return bool;
        }
    }
    return bool;
};

//the Neighborhood constructor is not intended to be called
//by you, is only intended to be called by NeighborhoodGroup.
//likewise for all of it's prototype methods, except for zoomTo
function Neighborhood(name, polygon) {
    this.name = name;
    this.polygon = polygon;
    this.markers = [];
    this.markersVisible = false;
}

//addMarker utilizes googles geometry library!
Neighborhood.prototype.addMarker = function (marker) {
    var isInPoly = google.maps.geometry.poly.containsLocation(marker.getPosition(), this.polygon);
    if (isInPoly) {
        this.markers.push(marker);
    }
    return isInPoly;
};

Neighborhood.prototype.setMarkersVisible = function (bool) {
    for (var i = 0, len = this.markers.length; i < len; i++) {
        this.markers[i].setVisible(bool);
    }
    this.markersVisible = bool;
};

Neighborhood.prototype.zoomTo = function () {
    var bounds = new google.maps.LatLngBounds(),
        path = this.polygon.getPath(),
        map = this.polygon.getMap();
    path.forEach(function (obj, idx) {
        bounds.extend(obj);
    });
    map.fitBounds(bounds);
};

The following example utilizes googles places library to load up to 60 (actually I think it gets around 54 of them) different locations of Starbucks in Manhattan (I believe there are more than that, but this is googles results limitations). How it works is, in the initialize() function we setup the map, then use ajax to load our '36061_minimal.json' file which contains the neighborhood names and coordinates we need, then the [private] setupNeighborhoods() function utilizes that data to create polygons and add them to our instance of NeighborhoodGroup then the [private] loadPlaces() function is used to add marker objects to the map and also registers the marker with our instance of NeighborhoodGroup. On to the example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Manhattan Neighborhoods</title>
<!--
NeighborhoodGroup.js requires that the geometry library be loaded,
just this example utilizes the places library
-->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=geometry,places"></script>
<script type="text/javascript" src="NeighborhoodGroup.js"></script>
<script>

/***
The '36061_minimal.json' file is derived from '36061.json' file
obtained from the-neighborhoods-project at:
http://zetashapes.com/editor/36061
***/

//for this example, we will just be using random colors for our polygons, from the array below
var aBunchOfColors = [
'Aqua', 'Aquamarine', 'Blue', 'BlueViolet', 'Brown', 'BurlyWood', 'CadetBlue', 'Chartreuse', 'Chocolate', 'Coral', 'CornflowerBlue', 'Crimson', 'Cyan', 'DarkBlue', 'DarkCyan', 'DarkGoldenRod', 'DarkGray', 'DarkGreen', 'DarkKhaki', 'DarkMagenta', 'DarkOliveGreen', 'Darkorange', 'DarkOrchid', 'DarkRed', 'DarkSalmon', 'DarkSeaGreen', 'DarkSlateBlue', 'DarkSlateGray', 'DarkTurquoise', 'DarkViolet', 'DeepPink', 'DeepSkyBlue', 'DodgerBlue', 'FireBrick', 'ForestGreen', 'Fuchsia', 'Gold', 'GoldenRod', 'Gray', 'Green', 'GreenYellow', 'HotPink', 'IndianRed', 'Indigo', 'LawnGreen', 'Lime', 'LimeGreen', 'Magenta', 'Maroon', 'MediumAquaMarine', 'MediumBlue', 'MediumOrchid', 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue', 'MediumSpringGreen', 'MediumTurquoise', 'MediumVioletRed', 'MidnightBlue', 'Navy', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed', 'Orchid', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed', 'Peru', 'Pink', 'Plum', 'Purple', 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Salmon', 'SandyBrown', 'SeaGreen', 'Sienna', 'SkyBlue', 'SlateBlue', 'SlateGray', 'SpringGreen', 'SteelBlue', 'Tan', 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'Yellow', 'YellowGreen'
];

Array.prototype.randomItem = function () {
    return this[Math.floor(Math.random()*this.length)];
};

function initialize() {
    var i,
        hoodGroup = new NeighborhoodGroup('Manhattan'),
        polys = [],
        gm = google.maps,
        xhr = getXhr(), //will use this to load json via ajax
        mapOptions = {
            zoom: 11,
            scaleControl: true,
            center: new gm.LatLng(40.79672159345707, -73.952665677124),
            mapTypeId: gm.MapTypeId.ROADMAP,
        },
        map = new gm.Map(document.getElementById('map_canvas'), mapOptions),
        service = new google.maps.places.PlacesService(map),
        infoWindow = new gm.InfoWindow();

    function setMarkerClickHandler(marker, infoWindowContent) {
        google.maps.event.addListener(marker, 'click', function () {
            if (!(infoWindow.anchor == this) || !infoWindow.isVisible) {
                infoWindow.setContent(infoWindowContent);
                infoWindow.open(map, this);
            } else {
                infoWindow.close();
            }
            infoWindow.isVisible = !infoWindow.isVisible;
            infoWindow.anchor = this;
        });
    }

     /*******
     * the loadPlaces function below utilizes googles places library to load
     * locations of up to 60 starbucks stores in Manhattan. You should replace
     * the code in this function with your own to just add Marker objects to
     *the map, though it's important to still use the line below which reads:
     *                  hoodGroup.addMarker(marker);
     * and I'd also strongly recommend using the setMarkerClickHandler function as below
     *******/
    function loadPlaces() {
        var placesResults = [],
            request = {
                location: mapOptions.center,
                radius: 25 / 0.00062137, //25 miles converted to meters
                query: 'Starbucks in Manhattan'
        };
        function isDuplicateResult(res) {
            for (var i = 0; i < placesResults.length; i++) {
                if (res.formatted_address == placesResults[i].formatted_address) {
                    return true;
                }
            }
            placesResults.push(res);
            return false;
        }
        service.textSearch(request, function (results, status, pagination) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                for (var res, marker, i = 0, len = results.length; i < len; i++) {
                    res = results[i];
                    if (!isDuplicateResult(res)) {
                        marker = new google.maps.Marker({
                            map: map,
                            visible: false,
                            position: res.geometry.location
                        });
                        setMarkerClickHandler(marker, res.name + '<br>' + res.formatted_address);
                        hoodGroup.addMarker(marker);
                    }
                }
            }
            if (pagination && pagination.hasNextPage) {
                pagination.nextPage();
            }
        });
    }

    function setupNeighborhoods(arr) {
        var item, poly, j,
            i = 0,
            len = arr.length,
            polyOptions = {
                strokeWeight: 0, //best with no stroke outline I feel
                fillOpacity: 0.4,
                map: map
            };
        for (; i < len; i++) {
            item = arr[i];
            for (j = 0; j < item[1][0].length; j++) {
                var tmp = item[1][0][j];
                item[1][0][j] = new gm.LatLng(tmp[1], tmp[0]);
            }
            color = aBunchOfColors.randomItem();
            polyOptions.fillColor = color;
            polyOptions.paths = item[1][0];
            poly = new gm.Polygon(polyOptions);
            hoodGroup.addNeighborhood(item[0], poly);
        }
        loadPlaces();
    }
    //begin ajax code to load our '36061_minimal.json' file
    if (xhr !== null) {
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    setupNeighborhoods(eval('(' + xhr.responseText + ')'));
                } else {
                    alert('failed to load json via ajax!');
                }
            }
        };
        xhr.open('GET', '36061_minimal.json', true);
        xhr.send(null);
    }
}

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

function getXhr() {
    var xhr = null;
    try{//Mozilla, Safari, IE 7+...
        xhr = new XMLHttpRequest();
        if (xhr.overrideMimeType) {
            xhr.overrideMimeType('text/xml');
        }
    } catch(e) {// IE 6, use only Msxml2.XMLHTTP.(6 or 3).0,
         //see: http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
        try{
            xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        }catch(e){
            try{
                xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0");
            }catch(e){}
        }
    }
    return xhr;
}

</script>
</head>
<body>
<div id="map_canvas" style="width:780px; height:600px; margin:10px auto;"></div>
</body>
</html>

javascript - Drawing Clean Neighborhood Boundaries on Google Maps - St...

javascript jquery google-maps
Rectangle 27 0

<?php 
$geolocation = $latitude.','.$longitude;
$request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false'; 
$file_contents = file_get_contents($request);
$json_decode = json_decode($file_contents);
if(isset($json_decode->results[0])) {
    $response = array();
    foreach($json_decode->results[0]->address_components as $addressComponet) {
        if(in_array('political', $addressComponet->types)) {
                $response[] = $addressComponet->long_name; 
        }
    }

    if(isset($response[0])){ $first  =  $response[0];  } else { $first  = 'null'; }
    if(isset($response[1])){ $second =  $response[1];  } else { $second = 'null'; } 
    if(isset($response[2])){ $third  =  $response[2];  } else { $third  = 'null'; }
    if(isset($response[3])){ $fourth =  $response[3];  } else { $fourth = 'null'; }
    if(isset($response[4])){ $fifth  =  $response[4];  } else { $fifth  = 'null'; }

    if( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth != 'null' ) {
        echo "<br/>Address:: ".$first;
        echo "<br/>City:: ".$second;
        echo "<br/>State:: ".$fourth;
        echo "<br/>Country:: ".$fifth;
    }
    else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth == 'null'  ) {
        echo "<br/>Address:: ".$first;
        echo "<br/>City:: ".$second;
        echo "<br/>State:: ".$third;
        echo "<br/>Country:: ".$fourth;
    }
    else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth == 'null' && $fifth == 'null' ) {
        echo "<br/>City:: ".$first;
        echo "<br/>State:: ".$second;
        echo "<br/>Country:: ".$third;
    }
    else if ( $first != 'null' && $second != 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
        echo "<br/>State:: ".$first;
        echo "<br/>Country:: ".$second;
    }
    else if ( $first != 'null' && $second == 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
        echo "<br/>Country:: ".$first;
    }
  }
?>

Its working .Thanks a lot!

google maps - Get location from latitude and longitude in php - Stack ...

php google-maps geolocation
Rectangle 27 0

It appears that you are reaching the API quotas.

This is triggered by too many requests from the same IP in a given day or too many in a period of time.

Try implementing a pause every 50-100 datasets to see if that helps with the first set of quotas.

The other would be to look at the API premier which might have higher quotas.

Check this out for another response on the same lines.

If you are able to pick up on the status codes, if you get the TOO_MANY_Queries, it appears that in their Python code, they execute a 2.0s delay.

Perhaps looking at doing something like that where you apply a 2s delay between each ForEach, or loop until you hit the limit, sleep(2) and then resume and see if that works.

The big thing here is you do not want get placed on the black list. Do you need to run all 1500 in 10-30 seconds? or if you implement a 2s delay between each, you would be looking at 3000s, or for your code to complete in 50 minutes and you would still have 1,000 calls left in your quota for that 24 hour period.

I would HIGHLY recommend building in safeguards from approaching the 2500 limit in a 24 hour period.

I'm not so sure. The limit per day is 2500. Its also not clear if the timeout has to do with script execution, or with the API.

php - Big Foreach Loop with Google Maps API - Stack Overflow

php mysql google-maps-api-3
Rectangle 27 0

<?php

/* 
* Given longitude and latitude in North America, return the address using The Google Geocoding API V3
*
*/

function Get_Address_From_Google_Maps($lat, $lon) {

$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";

// Make the HTTP request
$data = @file_get_contents($url);
// Parse the json response
$jsondata = json_decode($data,true);

// If the json data is invalid, return empty array
if (!check_status($jsondata))   return array();

$address = array(
    'country' => google_getCountry($jsondata),
    'province' => google_getProvince($jsondata),
    'city' => google_getCity($jsondata),
    'street' => google_getStreet($jsondata),
    'postal_code' => google_getPostalCode($jsondata),
    'country_code' => google_getCountryCode($jsondata),
    'formatted_address' => google_getAddress($jsondata),
);

return $address;
}

/* 
* Check if the json data from Google Geo is valid 
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
* Given Google Geocode json, return the value in the specified element of the array
*/

function google_getCountry($jsondata) {
    return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"]);
}
function google_getProvince($jsondata) {
    return Find_Long_Name_Given_Type("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
}
function google_getCity($jsondata) {
    return Find_Long_Name_Given_Type("locality", $jsondata["results"][0]["address_components"]);
}
function google_getStreet($jsondata) {
    return Find_Long_Name_Given_Type("street_number", $jsondata["results"][0]["address_components"]) . ' ' . Find_Long_Name_Given_Type("route", $jsondata["results"][0]["address_components"]);
}
function google_getPostalCode($jsondata) {
    return Find_Long_Name_Given_Type("postal_code", $jsondata["results"][0]["address_components"]);
}
function google_getCountryCode($jsondata) {
    return Find_Long_Name_Given_Type("country", $jsondata["results"][0]["address_components"], true);
}
function google_getAddress($jsondata) {
    return $jsondata["results"][0]["formatted_address"];
}

/*
* Searching in Google Geo json, return the long name given the type. 
* (If short_name is true, return short name)
*/

function Find_Long_Name_Given_Type($type, $array, $short_name = false) {
    foreach( $array as $value) {
        if (in_array($type, $value["types"])) {
            if ($short_name)    
                return $value["short_name"];
            return $value["long_name"];
        }
    }
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

Feel free to look at my blog for a sample code of how using the code above and sample result.

geolocation - PHP Latitude Longitude to Address - Stack Overflow

php geolocation location latitude-longitude
Rectangle 27 0

<?php 
$from = "sr nagar,hyderabad";
$to = "kukatpalle,hyderabad";
$from = urlencode($from);
$to = urlencode($to);
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);
$time = 0;
$distance = 0;
foreach($data->rows[0]->elements as $road) {
    $time += $road->duration->value;
    $distance += $road->distance->value;
}
echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
echo "Time: ".$time." seconds";
echo "<br/>";
echo "Distance: ".$distance." meters";
?>

Note : above you need to km and time h:m format just replace with

$time      = $road->duration->text;
$distance  = $road->distance->text;

php - How to calculate the distance between two addresses - Stack Over...

php api openstreetmap street-address
Rectangle 27 0

<?php 
$from = "kathmandu,nepal";
$to = "mahendranagar,nepal";
$from = urlencode($from);
$to = urlencode($to);
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);
$time = 0;
$distance = 0;
foreach($data->rows[0]->elements as $road) {
    $time += $road->duration->value;
    $distance += $road->distance->value;
}
echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
$distance=$distance/1000;
echo "Distance: ".$distance." km";
$default_price=11;
$distance_mile=$distance*1.6;
$price_distance=$default_price*$distance_mile;

if($distance_mile>=25){
    echo "<script>alert('We are sorry. Your address falls outside of our service area and we are unable to deliver/pick up equipment to you at this time.');</script>";
}
elseif($price_distance>=500){
    $price=$price_distance;
}else{
    if($distance_mile<5){
        $price=$price_distance;
    }elseif($distance_mile>5 && $distance_mile<10){
        $price=$default_price + 20;
    }
    elseif($distance_mile>10 && $distance_mile<25){
        $price=$default_price + 30;
    }
}
echo "final price : ".$price;
?>

wordpress - Calculate distance between two address php - Stack Overflo...

php wordpress google-maps woocommerce
Rectangle 27 0

You need to set the imagePath property of the MarkerClusterer correctly (to a location that contains the images for the clusters). One possible source is the google sample:

var markerCluster = new MarkerClusterer(map, markers,
   {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
var map, infoBubble;

function initialize() {
  var mapCenter = new google.maps.LatLng(52.5167, 13.3833);
  $('#user_latitude').val(52.5167);
  $('#user_longitude').val(13.3833);

  var mapOptions = {
    zoom: 3,
    center: mapCenter,
    zoomControl: true,
    zoomControlOptions: {
      position: google.maps.ControlPosition.LEFT_CENTER
    },
    streetViewControl: true,
    streetViewControlOptions: {
      position: google.maps.ControlPosition.LEFT_TOP
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    minZoom: 3,
    scrollwheel: false
  };


  var infowindow = new google.maps.InfoWindow();


  map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var markers = [];
  //       <?php foreach($pets as $pet):?>
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(52.5167, 13.3833),
    /*<?php //if():?>
    icon: 'http://cdn.com/my-custom-icon.png',
    <?php //else:?>
    icon: 'http://cdn.com/my-custom-icon.png',
    <?php //endif;?>*/
  });
  markers.push(marker);
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(52.5167, 13.38),
    /*<?php //if():?>
    icon: 'http://cdn.com/my-custom-icon.png',
    <?php //else:?>
    icon: 'http://cdn.com/my-custom-icon.png',
    <?php //endif;?>*/
  });
  markers.push(marker);
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(52.51, 13.3833),
    /*<?php //if():?>
    icon: 'http://cdn.com/my-custom-icon.png',
    <?php //else:?>
    icon: 'http://cdn.com/my-custom-icon.png',
    <?php //endif;?>*/
  });
  markers.push(marker);
  //        <?php endforeach;?>
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
  });



}


google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="map"></div>
<input id="user_latitude" />
<input id="user_longitude" />

javascript - Google maps MarkerClusterer displaying number instead of ...

javascript google-maps google-maps-api-3 markerclusterer
Rectangle 27 0

<?php
$from = "erode";
$to = "Chennai";

$from = urlencode($from);
$to = urlencode($to);

$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);

$time = 0;
$distance = 0;

foreach($data->rows[0]->elements as $road) {
    $time += $road->duration->value;
    $distance += $road->distance->value;
}
$km=$distance/1000;
echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
echo "Time: ".$time." seconds";
echo "<br/>";
echo "Distance: ".$distance." meters";
echo "<br/>";
echo $km;
?>

Using PHP/Google Maps to Calculate Distances - Stack Overflow

php maps
Rectangle 27 0

<h3>Images From Google </h3>
<?php

$company_name = 'walmart';
$data_ref = file_get_contents("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=Latitude ,Longitude&radius=100&name=".$company_name."&types=store&sensor=false&key=MYKEY");


$data_ref_de = json_decode($data_ref);

if($data_ref_de->status=='OK')
{


    foreach($data_ref_de->results as $result)
    {
        if(isset($result->photos) && count($result->photos))
        {
            foreach($result->photos as $photos)
            {?>
               //Display Image

            <img src="https://maps.googleapis.com/maps/api/place/photo?maxwidth=600&photoreference=<?php echo $photos->photo_reference; ?>&sensor=true&key=MYKEY" />

            <?php 
            }
        }
    }

}

And also be sure that you have enabled the Places API Service

php - Google Place Photo Requests Broken? - Stack Overflow

php google-places-api google-places
Rectangle 27 0

Thanks @Aaron for pointing out the PHP command BCCOMP. I used it to solve the issue.

Here is the code now:

$url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=".urlencode($address);

$lat_long = get_object_vars(json_decode(file_get_contents($url)));
// pick out what we need (lat,lng)
$lat = $lat_long['results'][0]->geometry->location->lat;
$lng = $lat_long['results'][0]->geometry->location->lng;

$propertyexist = FALSE; 

    // Check to see if Property is already in database  
    $getlatlng = sprintf("SELECT * FROM `Property`");
    $resultlatlng = $PDO_DB->query($getlatlng);
    $rowlatlng = $resultlatlng->fetchALL(PDO::FETCH_ASSOC);

    foreach ($rowlatlng AS $rowlt) {
        $checklat = bccomp($rowlt['lat'], $lat, 6);
        $checklng = bccomp($rowlt['lng'], $lng , 6);

        if (($checklat === 0) && ($checklng === 0)) {
            $propertyexist = TRUE;
            break;
        }
    }

php - Check if Latitiude & Longitude exist in database - Stack Overflo...

php mysql google-maps google-maps-api-3 floating-point
Rectangle 27 0

<?php
class GoogleGeo {
    public static function buildStaticMap($center, $markers=array(), $width=400, $height=400, $zoom=12, $directions=null) {
        $strMarkers = "";
        foreach($markers as $marker) {
            if (!empty($strMarkers)) $strMarkers .= '|';
            $strMarkers .= urlencode($marker);
        }
        if ($width > 640) $width = 640;
        if (!empty($center)) {
            $center = "&center=".$center;
        }
        if (!empty($strMarkers)) {
            $strMarkers = "&markers=".$strMarkers;
        }
        if ($zoom > 0) {
            $zoom = "&zoom=$zoom";
        }

        $steps = "";
        if (!empty($directions)) {
            foreach($directions['Directions']['Routes'][0]['Steps'] as $step) {
                $lat = $step['Point']['coordinates'][2];
                $lon = $step['Point']['coordinates'][0];
                if (!empty($steps)) $steps .= "|";
                $steps .= $lat.",".$lon;
            }
            if (!empty($steps)) {
                $steps .= "|".$directions['Directions']['Routes'][0]['End']['coordinates'][3].",".$directions['Directions']['Routes'][0]['End']['coordinates'][0];
                $steps = "&path=rgb:0x0000ff,weight:5|".$steps;
            }
        }

        $staticMap = "http://maps.google.com/staticmap?maptype=mobile&size=".$width."x$height&maptype=roadmap&key=".GOOGLE_MAPS_KEY."&sensor=false$strMarkers$center$zoom$steps";
        return $staticMap;
    }

    public static function retrieveDirections ($from, $to) {
        $params = array('key' => GOOGLE_MAPS_KEY, 'output' => 'json', 'q' => "from: $from to: $to");
        $url = "http://maps.google.com/maps/nav";
        $result = HttpHelper::doGET($url, $params);
        $result = json_decode($result, true);
        return $result;
    }
}
?>
<?php
...
    /* FROM and TO coordinates */
    $markers = array("37.262568,-121.962232,redr", "37.229898,-121.971853,blueg");
    /* Get the driving directions from google api */
    $directions = GoogleGeo::retrieveDirections("485 Alberto Way, Suite 210. Los Gatos, CA 95032", "14109 Winchester Bl, Los Gatos, CA");
    /* Create the map image url with the directions coordinates */
    $staticMap = GoogleGeo::buildStaticMap(null, $markers, 640, 240, null, $directions);
....
?>

where is the class HttpHelper written? I'm getting the error Class 'HttpHelper' not found. Should I be able to just paste this code and change the $markers and $direction variable for this to work on my site?

in the blog he notes: Note that HttpHelper::doGET downloads the string, you can substitute that part with CURL or fopen.

create google maps to plot driving route to multiple location - Stack ...

google-maps