Javascript google geolocation is not working in live site - php

Google geolocation with Javascript is not working in live site for major browsers like Firefox, Chrome. Geolocation result is displaying in Opera for live site, where as the same is working in localhost for all browsers (Chrome, firefox & Opera). My Live site protocol using https://. See below code and suggest any..
Geolocation and Google Maps API
<script src="http://maps.google.com/maps/api/js?key=MY_KEY_HERE&sensor=true"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": latLng
},
function(results, status) {
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//alert(city.short_name + " " + city.long_name);
//alert(city.long_name);
var cityname = city.long_name;
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("address").innerHTML = results[0].formatted_address;
document.getElementById("citynm").innerHTML = cityname; }
else {
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br>"; }
});
}
function geolocationSuccess(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
writeAddressName(userLatLng);
var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
// Draw a circle around the user position to have an idea of the current localization accuracy
var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
}
function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br>";
}
function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation)
{
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
</head>
<body>
<p id="citynm"></p>
<p id="address"></p>
</body>
</html>

I have tested you codes (Chrome v29, Windows 8), the one below works from a remote server (non-local host) but you need note note 2 areas
<script src="http://maps.google.com/maps/api/js?v=3.9&sensor=true"></script>
I added v=3.9
And
function writeAddressName(latLng) {
...
if (results[0].address_components[i].types[b] == "route") {
You may need to handle case where city cannot be set.
I can see the address. [This sample does not include map display]
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?v=3.9&sensor=true"></script>
<script>
function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ "location": latLng }, function(results, status) {
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "route") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//alert(city.short_name + " " + city.long_name);
//alert(city.long_name);
var cityname = city.long_name;
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("address").innerHTML = results[0].formatted_address;
document.getElementById("citynm").innerHTML = cityname;
}
else {
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br>";
}
});
}
function geolocationSuccess(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
writeAddressName(userLatLng);
var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
// Draw a circle around the user position to have an idea of the current localization accuracy
var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
}
function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br>";
}
function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation) {
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
</head>
<body>
<p id="error"></p>
<p id="citynm"></p>
<p id="address"></p>
</body>
</html>

May be this links can help you
https://developers.google.com/maps/articles/geocodestrat
google maps api works at localhost but doesn't work at web server

https://developers.google.com/maps/faq?hl=en&csw=1#browsersupport
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
http://jsfiddle.net/BQzLq/3/
https://support.google.com/maps/answer/21849?hl=en
http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
These all links is just for your knowledge in some browser or browser's older versions google map v3 doesn't works.

Related

I have x and y coordinates in my map. The coordinates of x are different marker and have a bevel. Also in y. How can I do it in the following code?

I have x and y coordinates in my map. The coordinates of x are different marker and have a bevel. Also in y.
How can I do it in the following code?
<div id="map"></div>
<div id="right-panel">
<p>Total Distance: <span id="total"></span></p>
</div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -24.345, lng: 134.46} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: false,//marker hareketi sabit
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('Malatya', 'Malatya', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
waypoints: [<?=$directions?>],
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';
}

saving marker data into db

How to save a google maps marker data into mysql DB ? using php .
And is it possible to prevent dragging that marker out of a certain country ? or maybe validating if the data is out of the wanted country when clicking on submit for example.
Yes, no problem.
The database part, you will have to do yourself. I provide you 'ajax.php'; where you receive the POST data. All I do, is print the SQL-string.
The country is Belgium, feel free to change this (now on line 39). When ever the client drops the marker anywhere but in Belgium, the marker is sent back to the position where the client started dragging
ajax.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO markers (lat, lng) VALUES (". (float) $_POST['lat'] .", ". (float) $_POST['lng'] .");";
echo $sql;
}
?>
index.php
<div id="map-canvas"></div>
<div class="controls">
<input type="button" value="SAVE" id="save_marker">
</div>
<div id="display"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script>
///////////////////////
// Ajax / upload part
$(document).ready(function() {
// initialize Google Maps
initialize();
// save marker to database
$('#save_marker').click(function() {
// we read the position of the marker and send it via AJAX
var position = marker.getPosition();
$.ajax({
url: 'ajax.php',
type: 'post',
data: {
lat: position.lat(),
lng: position.lng()
},
success: function(response) {
// we print the INSERT query to #display
$('#display').html(response);
}
});
});
});
///////////////////////
//Google Maps part
var map = null;
var marker = null;
var country = 'BE'; // Belgium. Feel free to use this script on any other country
// Google Maps
function initialize() {
var startDragPosition = null;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(50.5, 4.5), // Over Belgium
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// set the new marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(50.5, 4.5),
map: map,
draggable: true
});
var myGeocoder = new google.maps.Geocoder();
// set a callback for the start and end of dragging
google.maps.event.addListener(marker,'dragstart',function(event) {
// we remember the position from which the marker started.
// If the marker is dropped in an other country, we will set the marker back to this position
startDragPosition = marker.getPosition();
});
google.maps.event.addListener(marker,'dragend',function(event) {
// now we have to see if the country is the right country.
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results[1]) {
var countryMarker = addresComponent('country', results[1], true);
if (country != countryMarker) {
// we set the marker back
marker.setPosition(startDragPosition);
}
}
else {
// geocoder didn't find anything. So let's presume the position is invalid
marker.setPosition(startDragPosition);
}
});
});
}
/**
* geocodeResponse is an object full of address data.
* This function will "fish" for the right value
*
* example: type = 'postal_code' =>
* geocodeResponse.address_components[5].types[1] = 'postal_code'
* geocodeResponse.address_components[5].long_name = '1000'
*
* type = 'route' =>
* geocodeResponse.address_components[1].types[1] = 'route'
* geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse, shortName) {
for(var i=0; i < geocodeResponse.address_components.length; i++) {
for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
if (geocodeResponse.address_components[i].types[j] == type) {
if (shortName) {
return geocodeResponse.address_components[i].short_name;
}
else {
return geocodeResponse.address_components[i].long_name;
}
}
}
}
return '';
}
</script>
<style>
#map-canvas {
height:400px;
}
</style>

Getting current zoom level from a Google Map

I am using a google map in a PHP/MYSQL application. I get the code for the map form Goolge Docs and adapted a bit for the application.
New modifications are comming in the application and now the application need to know the 'current zoom level of the google map'. I check in internet but I didn't find a clear answer.
Is it possible to do it ? Is it mandatory to reload the page in every zoom change ?
This is the code and thanks.
<code>
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(latitude,longitude),
zoom: zoommapa,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: 'roadmap'
});
// drap center
var image = 'images/icons/etapa/etapa.png';
var myLatLng = new google.maps.LatLng(latitude,longitude);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("marquers_motor_3.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//var name = 1;
var markers2 = [];
for (var i = 0; i < markers.length; i++) {
//var name = markers[i].getAttribute("name");
var image = markers[i].getAttribute("image");
var sombra = markers[i].getAttribute("sombra");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var orden = markers[i].getAttribute("order");
var name = markers[i].getAttribute("name"); // web_site email ciudad pais
var web_site = markers[i].getAttribute("web_site");
var email = markers[i].getAttribute("email");
var ciudad = markers[i].getAttribute("ciudad");
var pais = markers[i].getAttribute("pais");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
if (ciudad =="" || ciudad =='Desconocido') { ciudad = ""} else {ciudad =ciudad + " " }
if (!(web_site =="")) {web_site = "<a href='" + web_site + "' class='list' target='_blank'>" + web_site +"</a>"+"<br>"} else {web_site =""}
var html = "<div id='infoWindow'>" + orden + " - " + name + "<br>" + web_site + ciudad + " " + pais + "</div>";
//var name = name + 1;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image,
shadow: sombra
});
var marker2 = new google.maps.Marker({
position: point
});
markers2.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
});
var mcOptions = {gridSize: 50, maxZoom: 15};
var MarkerClusterer = new MarkerClusterer(map, markers2,mcOptions);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
//google.maps.event.addDomListener(window, 'load', initialize);
I assume the application needs to know the zoom level, but the zoom level is in user space (client side).
get the zoom level from the map with javascript (see https://developers.google.com/maps/documentation/javascript/reference?hl=nl#Map)
map.getZoom();
This has to be send back to the server using AJAX calls
Server can do with the zoom level what it wants
Keep in mind the fact that if multiple users can open the same map, zoom levels can be different so what would be the required behavior?
Yes, you can get the current zoom level of the map with the getZoom method of the google.maps.Map object.
If you need to trigger a method when the zoom changed then you can listen to the zoom_changed event of the google.maps.Map object. For further information about google.maps.Map object read: this
Consider the following example (to make it work: copy in notepad save the file as html and run it with Chrome):
<!DOCTYPE html>
<html>
<head>
<title>Getting Zoom Demo</title>
<style type="text/css">
html, body{ height: 100%; height: 100%; margin: 0; padding: 0; }
#map-container{ height: 100%; width: 100%; min-width:500px; min-height:300px; }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
<body>
<div>
<label id="display-zoom-label">
</label>
</div>
<div id="map-container"></div>
<script>
// Global map variable to have access to map object everywhere in the code
var map,
firstBoundChangedListener,
markers = [];
// Add random markers
function addMarkers(count) {
// map is the google.maps.Map object
var bounds = map.getBounds();
var northEast = bounds.getNorthEast();
var southWest = bounds.getSouthWest();
var minLat = Math.min(northEast.lat(), southWest.lat());
var maxLat = Math.max(northEast.lat(), southWest.lat());
var minLng = Math.min(northEast.lng(), southWest.lng());
var maxLng = Math.max(northEast.lng(), southWest.lng());
var latDifference = maxLat - minLat;
var lngDifference = maxLng - minLng;
var latLngArray = new Array();
for (var i = 0; i < count; i++) {
var lat = minLat + Math.random() * latDifference;
var lng = minLng + Math.random() * lngDifference;
var latLng = new google.maps.LatLng(lat, lng);
latLngArray.push(latLng);
}
for (var i = 0; i < latLngArray.length; i++) {
var marker = new google.maps.Marker({
position: latLngArray[i],
title: "Marker: " + i
});
markers.push(marker);
marker.setMap(map);
}
}
function UpdateZoomLabel() {
var displayZoomLabel = document.getElementById("display-zoom-label"),
// get current zoom
zoomValue = map.getZoom();
displayZoomLabel.innerHTML = "The Current Map's Zoom is: " + zoomValue;
}
// Initialize the map object
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-container'), mapOptions);
firstBoundChangedListener = google.maps.event.addListener(map, "bounds_changed", function () {
if (firstBoundChangedListener) google.maps.event.removeListener(firstBoundChangedListener);
// call add markers: add 'n' markers randomly
addMarkers(6);
});
//Listen for the 'zoom_changed' event of the map
google.maps.event.addListener(map, "zoom_changed", function () {
//show zoom in label
UpdateZoomLabel();
});
UpdateZoomLabel();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>

Facing the targeted building with Google StreetView

My question is very straightforward.
I need the heading value to know how to target the POV.
sv.getPanoramaByLocation() in this case returns a data variable containing the heading of both the arrows in which direction you can go further.
However it doesn't give me the heading value for which way to look at the building. However it is possible to use a marker in streetview to target your building! example
Can anyone help me with this? I can make whatever dump you people want.
Geocode the address of the building you want to "look at". Use the geometry library
computeHeading(from:LatLng, to:LatLng) function to calculate the heading between the StreetView location and the building.
(assumes that the geocoder returns a "rooftop" geocode)
example (Statue of Liberty)
another option, use the directions service:
related question: Request main road StreetView panoramas instead of back alleys from API
code snippet that uses the directions service to get a location on the road to use for street view "camera" location (works better now that you can get "interior" streetview locations returned):
var map;
var berkeley = new google.maps.LatLng(37.869085, -122.254775);
var sv = new google.maps.StreetViewService();
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
var panorama;
var myLatLng;
var address = "525 Beacon St. Boston, MA";
function initialize() {
panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
directionsService.route({
origin: address,
destination: address,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// myLatLng = response.routes[0].legs[0].start_location;
sv.getPanoramaByLocation(response.routes[0].legs[0].start_location, 50, processSVData);
var marker = new google.maps.Marker({
position: response.routes[0].legs[0].start_location,
map: map,
title: "Directions"
});
map.setCenter(myLatLng);
} else document.getElementById('info').innerHTML += "status:"+status+"<br>";
});
geocoder.geocode({
'address': address
}, geocoderCallback);
// Set up the map
var myOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
panorama.setPano(data.location.pano);
var camera = new google.maps.Marker({
position: data.location.latLng,
map: map,
draggable: true,
title: "camera"
});
var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, myLatLng);
document.getElementById('info').innerHTML += "heading:"+heading+"<br>"
+ "location: "+myLatLng.toUrlValue(6)+"<br>"
+ "camera:"+data.location.latLng.toUrlValue(6)+"<br>";
// alert(data.location.latLng+":"+myLatLng+":"+heading);
panorama.setPov({
heading: heading,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
} else {
alert("Street View data not found for this location.");
}
}
function geocoderCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myLatLng = results[0].geometry.location;
map.setCenter(myLatLng);
if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport);
else if (results[0].geometry.bounds) map.fitBounds(results[0].geometry.bounds);
else map.setZoom(15);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: address
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
};
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="pano" style="width: 425px; height: 400px;float:left"></div>
<div id="info"></div>
<div id="map_canvas" style="width: 425px; height: 400px;float:left"></div>
<div id="map_center"></div>
<div id="streetview_pov"></div>

Reverse Geocode On Google Maps api v3

I wonder whether someone may be able to help me please.
I using the code shown below to correctly plot markers retrieved from a MySQL database on a Google Map.
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("images/location-marker-2.png")
new google.maps.Point(16, 32);
var center = null;
var map = null;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 6,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
<?php
include("admin/link.php");
include("admin/opendb.php");
$query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
while ($row = mysql_fetch_array($query)){
$locationname=$row['locationname'];
$osgb36lat=$row['osgb36lat'];
$osgb36lon=$row['osgb36lon'];
echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
}
mysql_close($connect);
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
What I'm now trying to do is add further functionality that allows users to also click on the map to plot new markers, in essence using the pre-existing marker from the database as a point to work from, performing a reverse geocode.
I've been researching this for a number of days now and I've tried to implement a whole host of tutorials, but I just can't seem to get both parts of the functionality working.
I do know that to enable a on-click event I need to incorporate something along the lines of:
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng)
geocode_lookup( 'latLng', event.latLng );
});
}
but I must admit I'm a little unsure about what else I need to incorporate.
I just wondered whether someone may be able to take a look at this please, and I'd be very grateful if someone could show me where I've gone wrong.
Many thanks and kind regards
I wrote a separate maps page with just click-to-reverse-geocode functionality
http://jsfiddle.net/ZDQeM/
The address details are confusing to work with, I think. The results are an array, at different levels of precision, one might include the county, another the state, another the street address. Generally I only use results[0]. The details are in the docs: https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingResponses
If you need specific information the sure way to obtain it is iterate through the whole results array until you find what you need (types[] containing postal_code, for example).
google.maps.event.addListener(map, 'click', function(event) {
userMarker = new google.maps.Marker({
map: map,
position: event.latLng
});
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
else {
alert("No results");
}
}
else {
alert("Geocoding unsuccessful: Status " + status);
}
});
});
Where in your code?
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("images/location-marker-2.png")
new google.maps.Point(16, 32);
var center = null;
var map = null;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 6,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
<?php
include("admin/link.php");
include("admin/opendb.php");
$query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
while ($row = mysql_fetch_array($query)){
$locationname=$row['locationname'];
$osgb36lat=$row['osgb36lat'];
$osgb36lon=$row['osgb36lon'];
echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
}
mysql_close($connect);
?>
center = bounds.getCenter();
map.fitBounds(bounds);
var geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, 'click', function(event) {
var userMarker = new google.maps.Marker({
map: map,
position: event.latLng
});
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
else {
alert("No results");
}
}
else {
alert("Geocoding unsuccessful: Status " + status);
}
});
});
}
</script>

Categories