I am using Google Maps V3 API and using its Geocoder to do reverse geocoding of the point on the map where the user clicks on.
Load the geocoding function when DOM is fully loaded
$(function() {
reverse_geocode(40.714224,-73.961452);
});
Function that does the reverse geocoding:
function reverse_geocode(lat,lng) {
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(10,-10);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert('asdasd');
} else {
alert("Geocoder failed due to: " + status);
}
});
}
If I call the reverse_geocode function when the page first loads, everything works fine and the alert() is called.
However, if I call reverse_geocode() only when triggered by a rightclick on the map followed by a mouseclick on a div, using the code below, nothing happens! Any idea what went wrong?
google.maps.event.addListener(map, "rightclick", function(event) {
//some code not shown
$("#info_rightclick_top").click(function(e) {
info_ok_handleclick();
});
});
function info_ok_handleclick() {
$("#info_ok").click(function(e) {
var lat = marker_search_location.getPosition().lat();
var lng = marker_search_location.getPosition().lng();
var latlng = lat + "_" + lng;
reverse_geocode(10,-10);
// some code hidden
});
Using this bellow code you can search a location by keywords.
<?php
include_once("include/GoogleMap.php");
include_once("include/JSMin.php");
$mapcity="India";
$mapdesc="description about this map";
$MAP_OBJECT = new GoogleMapAPI();
$MAP_OBJECT->_minify_js = isset($_REQUEST["min"])?FALSE:TRUE;
$MAP_OBJECT->addMarkerByAddress($mapcity,"Map name", $mapdesc);
$MAP_OBJECT->enableStreetViewControls();
?>
<html>
<head>
<?=$MAP_OBJECT->getHeaderJS();?>
<?=$MAP_OBJECT->getMapJS();?>
</head>
<body>
<?=$MAP_OBJECT->printOnLoad();?>
<?=$MAP_OBJECT->setMapType(ROADMAP);?>
<?=$MAP_OBJECT->printMap();?>
<?=$MAP_OBJECT->printSidebar();?>
</body>
</html>
Related
I'm using the following code to convert an address to longitude and latitude. The code is taken from http://www.phpmoot.com/php-get-latitudelongitude-from-an-address-with-google-map/
$address = '201 S. Division St., Ann Arbor, MI 48104'; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
echo $address.'<br>Lat: '.$lat.'<br>Long: '.$long;
This works fine on my previous hosting, but when I moved the site to TSO host, it no longer works. What reasons might there be for this?
I've tried using a browser api key in the url and a server api key and that doesn't work either. like this
http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key=****API_KEY_GOES_HERE****&sensor=false
Any help welcome. TSO Host support can't seem to figure it out.
Just to be sure it is server related I would recommend you to try using the JS in page. Please try to implement below code with changing your div ID and KEY. Also pass the address variable you have to related place.
<script>
function initialize() {
var center;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': $AdressYouGotFromThePost}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mycenter = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());//
var mapProp = {
center:mycenter,
zoom:11
};
var map=new google.maps.Map(document.getElementById("YOURDIVID"),mapProp);
var request = {
location: mycenter,
radius: '20000',
types: ['bar,night_club,cafe,museum,movie_theater,zoo,aquapark']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createPhotoMarker(results[i]);
}
}
}
function createPhotoMarker(place) {
var photos = place.photos;
if (!photos) {
return;
}
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name
//icon: photos[0].getUrl({'maxWidth': 55, 'maxHeight': 55})
});
//console.log(photos[0].getUrl({'maxWidth': 105, 'maxHeight': 105}));
var contenthtml = "<p>"+place.name+"</p><img src="+photos[0].getUrl({'maxWidth': 105, 'maxHeight': 105})+" width='105px'/>";
var infowindow = new google.maps.InfoWindow({
content:contenthtml
});
google.maps.event.addListener(marker,'click',function() {
map.setZoom(17);
map.setCenter(marker.getPosition());
infowindow.open(map,marker);
});
}
});
}
</script>
<script async="" defer="" src="https://maps.googleapis.com/maps/api/js?key=YOURACCESSKEYHERE&callback=initialize&libraries=places">
Using the php method to convert the address to longitude and latitude like this example http://www.phpmoot.com/php-get-latitudelongitude-from-an-address-with-google-map/
was causing the api limits to be reached on the TSO host shared cloud server. Using an API key didn't seem to make any difference. The solution was to not use the php method and instead use the Javascript method as per Googles example here - https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
I try to describe my issue as easy as possible..
When I submit a form, I need to call another function. I tried onSubmit, but unfortunately it doesnot work properly, as the function that I need to call is Google Maps API matter getting coordinates from textbox where a user is choosing the location.. The function is never called or it seems that it is called too late.. So I tried this:
<input type="button" value="Search" name="submitBtn" id="subBtn1" onclick="onSubmit1();">
and function onSubmit1() is as following:
function onSubmit1 () {
codeAddress();
// document.forms["searchForm"].submit();
}
After clicking the button, the function works.. codeAddress gets me the latitude and longitude from Google servers and pre-fills them to textboxes in my searchForm.
However, if I remove the doble slash and want to submit the form, the following happens:
form is submitted, but the latitude and longitude is always empty strings..
Any ideas.. Is it possible, that the second line in onSubmit1 function just doesnot wait for goole to do its job?
Thanks for any tips..
Please know, that the form and all its functions work perfectly if I for example set the coordinates by myself and submit the form then.. There is no problem in that
EDIT
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode(
{ 'address': address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
document.getElementById("my-lat").value = lat;
document.getElementById("my-lng").value = lng;
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
Your issue is that codeAddress is asynchronous (well the geocode method of the geocoder object is), and therefor returns immediately.
What you must do is only submit the form in the async callback:
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode(
{ 'address': address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
document.getElementById("my-lat").value = lat;
document.getElementById("my-lng").value = lng;
//now submit form
document.forms["searchForm"].submit();
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
I am trying to implement a php service that will take a $_GET("LAT") and a $_GET("LNG") and verify it against the Google StreetView API v3 JavaScript if it is valid or not.
If it is, it returns OK, or NOK.
I realize the JS code to accomplish that is:
var latLng = new google.maps.LatLng(12.121221, 78.121212);
streetViewService.getPanoramaByLocation(latLng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {
if (status === google.maps.StreetViewStatus.OK) {
//ok
} else {
//no ok
}
});
I am not being able though to tie everything together, meaning the PHP and JS, so that will work.
Can anyone please help me?
Thanks
EDIT 1:
This is the code I came up for far, but it does not work:
<?php
Header("content-type: application/javascript");
?>
<html>
<head> </head>
<body onload="checkValid()">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script language="text/javascript">
function checkValid() {
var streetViewService = new google.maps.StreetViewService();
var STREETVIEW_MAX_DISTANCE = 100;
var latLng = new google.maps.LatLng(<?php $_GET("LAT") ?>,<?php $_GET("LNG") ?>);
streetViewService.getPanoramaByLocation(latLng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {
if (status === google.maps.StreetViewStatus.OK) {
alert('ok');
} else {
alert('not');
}
});
}
</script>
</body>
</html>
If you want to use JS to verify the lat and lng then you need to get the $_GET parameters into the JS. Something like:
var LAT = '<?=isset($_GET['LAT']) ? $_GET['LAT'] : 91?>';
var LNG = '<?=isset($_GET['LNG']) ? $_GET['LNG'] : 181?>';
var latLng = new google.maps.LatLng(LAT, LNG);
streetViewService.getPanoramaByLocation(latLng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {
if (status === google.maps.StreetViewStatus.OK) {
//ok
} else {
//no ok
}
});
I've used a simple ternary statement asking if the GET is available, if it is, then add it to the JS variable, if it's not add a value outside of the range of Lat and Lng. This will cause the Google Maps API to fail automatically.
True say STREETVIEW_MAX_DISTANCE may help to you find nereast position where exist panarama, below code work, but it requre additional algorithm for find neares point
var myLatLng=new google.maps.LatLng(44.293232,-68.294734);
var streetViewService = new google.maps.StreetViewService();
var STREETVIEW_MAX_DISTANCE = 1050; //where we search nearest panoram
streetViewService.getPanoramaByLocation(myLatLng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {
console.log(":1111111111111111111:",streetViewPanoramaData, status);
if (status === google.maps.StreetViewStatus.OK) {
// ok
var panoramaOptions = {
position: streetViewPanoramaData.location.latLng, //this is what we found !!!!
pov: {
heading: 34,
pitch: 10
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('map_pano'), panoramaOptions);
map.setStreetView(panorama);
} else {
// no street view available in this range, or some error occurred
}
});
I'm developing a web page with a Google Maps API v3. I currently have a functional map and search bar. I need to be able to display the distance from a searched address to the nearest placemark on one of the KML files on the map. How can I do this?
Here is the code for the page:
<script type="text/javascript">
var geocoder;
var map;
var marker;
var layers = [];
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (41, -73.4);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
marker = new google.maps.Marker({map:map});
layers[0] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/South-and-North-County-Trailway.kml',
{preserveViewport: true});
layers[1] = new google.maps.KmlLayer('http://www.nyc.gov/html/dot/downloads/misc/cityracks.kml',
{preserveViewport: true});
layers[2] = new google.maps.KmlLayer('http://dl.dropbox.com/u/80233620/NWS%20Radar%20Images.kmz',
{preserveViewport: true});
for (var i = 0; i < layers.length; i++) {
layers[i].setMap(map);
}
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
marker.setPosition(results [0].geometry.location);
map.setZoom(14);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function toggleLayer(i) {
if(layers[i].getMap() === null) {
layers[i].setMap(map);
}
else {
layers[i].setMap(null);}
}
</script>
You cannot access the data in KML layers like that
https://developers.google.com/maps/documentation/javascript/layers#KMLLayers
Because KML may include a large number of features, you may not access
feature data from the KmlLayer object directly. Instead, as features
are displayed, they are rendered to look like clickable Maps API
overlays.
Instead you can process the XML and add markers manually, then use the geometry library and computeDistanceBetween() to get the distance. I usually multiply the distance by some number to account for turns (The distance formula gets a straight line distance). I believe around 1.2 was the most accurate.
Hi I am having issues inserting a map from google maps and using the send framework.
My issue is similar to Question 921811
However when adding the script to my view I am getting the googlemaps api in twice and no map being rendered by the view.
This is what I am adding to the view script
<?php
$this->headScript()->appendFile('http://maps.google.com/maps?file=api&;v=2&;sensor=true&;key=ABQIAAAAHSJ3TgOTyvA1VzwU8g4Y7RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxRmCy1h3nGv3n46kcqaFljsimqfWw');
$this->headScript()->appendScript(' var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
geocoder = new GClientGeocoder();
}
}
function showAddress(address) {
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}
}
');
?>
However this is adding the maps API in twice with a lot of escaped html, which is causing the maps to fail to load. e.g.
<script type="text/javascript" src="<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAHSJ3TgOTyvA1VzwU8g4Y7RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxRmCy1h3nGv3n46kcqaFljsimqfWw" type="text/javascript"></script>"></script>
<script type="text/javascript" src="http://maps.google.com/maps?file=api&;v=2&;sensor=true&;key=ABQIAAAAHSJ3TgOTyvA1VzwU8g4Y7RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxRmCy1h3nGv3n46kcqaFljsimqfWw"></script>
<script type="text/javascript">
//<!--
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
geocoder = new GClientGeocoder();
}
}
.....
Any idea why the google maps API is being added twice with the escaped html tags? I have no idea and the examples I have found don't seem to have this issue.
Thanks in advance
The reason you're not seeing any map is because the URL in your appendFile() call is broken. Remove all the semi-colons:
http://maps.google.com/maps?file=api&v=2&sensor=true&key=whatever
That will fix the second <script> tag and make the Google map actually work.
That still leaves you with the first <script> tag, though. But that must be related to how you're actually printing the contents of the HeadScript view helper. Can you show us what that code looks like?