How to calculate selected area longitude and latitude in google map? - php

I am using google map API integration.I need to get latitude and longitude from particular selected area in that map. In my script based on selected area in google map.
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<p> <div id="map" style="width:980px;height:480px;"></div></p>
In that script, i already create selected area in google map.but i need to get that particular selected area`s longitude and latitude.how to get selected area (cities and countries) value?

You can not get all the cities and countries inside an arbitrary polygon using the Google Maps API. You can get the city and country of a single point using the reverse geocoder using the Google Maps API v3 (or the web service), but an arbitrary polygon would be an infinite number of requests, and would tun into quota and rate limitations. If you have your own source of geographic data (say from geonames) in database that supports geographic queries, you can send the vertices of the polygon to your server and retrieve the locations in that polygon.

Related

Google map API Shows Blank Screen in my Laravel Application

In my Laravel Application i use google map to Display Route and Distance Between Two Places. after setting google map, i test my app. its display as Blank Screen. I even registered the application using a key that I applied for on Google's website. I have been working on this for 2 hours and cannot figure it out.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY API KEY&libraries=places&callback=initMap&sensor=false" async defer></script>
<script type="text/javascript">
function GetRoute() {
source = document.getElementById("pickupaddress").value;
destination = document.getElementById("deliveryaddress").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var dvDistance = document.getElementById("distanceops");
dvDistance.innerHTML = "";
dvDistance.innerHTML += distance;
} else {
alert("Unable to find the distance via road.");
}
});
}
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 4.2105, lng: 101.9758},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('pickupaddress');
var destinationInput = document.getElementById('deliveryaddress');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var deliveryrestrictOptions = {componentRestrictions: {country: 'my'},placeIdOnly: true};
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, deliveryrestrictOptions);
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput,deliveryrestrictOptions);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
GetRoute();
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
window.ParsleyConfig = {
errorsWrapper: '<div></div>',
errorTemplate: '<span class="error-text"></span>',
classHandler: function (el) {
return el.$element.closest('input');
},
successClass: 'valid',
errorClass: 'invalid'
};
</script>
I have worked on google maps. Google maps won't load inside a modal or any hidden divs (for perf reasons).
Here is what you do. Trigger resize on the map and it should render the map.
google.maps.event.trigger(map, 'resize') where map is your map instance name.

Drawing route on map, with multiple markers, CodeIgniter

I did my searching but unfortunately didnt find relevant solution. I want to do it by using codeigniter google map library. i am following this
link
But it is just showing starting and ending point, it's not creating multiple pins like
This is making multiple pins with polyline but i want routing like:
with multiple pins as shown in polyline map picture.. Is it posible to get multiple directions with multiple pins ??
I tried it but my trick couldn't work. i tried it by using while loop and i incremented the variable before ending point to make my direction like
1st lat, long : starting point
2nd lat, long : ending point
2nd lat, long : starting point
3rd lat, long : ending point
3rd lat, long : starting point
4th lat, long : ending point
But it's only making 1st and last ending point for start and end direction
Here is my controller function
##Load library
$this->load->library('googlemaps');
## Getting data from db
$final_data['final_data'] = $this->Main_manager->getAllEmailLogsById($id);
$email = $final_data['final_data'][0]['email'];
$date = $final_data['final_data'][0]['date'];
$file = 'assets/email_logs/'.$email.'-'.str_replace(' ','-',$date).'.txt';
## Getting lat long data from txt file
$logData = file_get_contents($file);
$logData = json_decode($logData, true);
$marker = array();
$logs = count($logData['logs']);
$config['center'] = $final_data['final_data'][0]['lat'].','. $final_data['final_data'][0]['long'];
$config['zoom'] = 'auto';
$i=0;
while($i<$logs-1):
$config['position'] = $logData['logs'][$i]['lat'].','. $logData['logs'][$i]['long'];
$config['infowindow_content'] = $logs['email'];
$config['animation'] = 'DROP';
$config['draggable'] = FALSE;
$config['directions'] = TRUE;
$config['directionsStart'] = $logData['logs'][$i]['lat'].','. $logData['logs'][$i]['long'];
$i++;
$config['directionsEnd'] = $logData['logs'][$i]['lat'].','. $logData['logs'][$i]['long'];
$config['directionsDivID'] = 'directionsDiv';
endwhile;
## initialize the map
$this->googlemaps->initialize($config);
##create map
$final_data['map'] = $this->googlemaps->create_map();
$this->load->view('administrator/header');
$this->load->view('administrator/view_logs_detail', $final_data);
It seems like you need to use google's DirectionsService.
This service Google map API key to draw routes
Get google key from here login to google account and generate key for your project
Working Demo
HTML
<h1>Google Map direction service</h1>
<div id="map"></div>
CSS
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
JS:
var map;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var locations = [
['Shahrah-e-Faisal, Karachi, Pakistan', 24.8678, 67.0842, 1],
['Tariq Rd, Karachi, Pakistan', 24.8727, 67.0604, 2],
['Service Lane, Karachi, Pakistan', 24.8161, 67.0212, 3]
];
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(24.8678, 67.0842),
});
directionsDisplay.setMap(map);
var infowindow = new google.maps.InfoWindow();
var marker, i;
var request = {
travelMode: google.maps.TravelMode.DRIVING
};
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
if (i == 0) request.origin = marker.getPosition();
else if (i == locations.length - 1) request.destination = marker.getPosition();
else {
if (!request.waypoints) request.waypoints = [];
request.waypoints.push({
location: marker.getPosition(),
stopover: true
});
}
}
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);

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>

How to allow the visitor to add any location to the map and how to save it in the database

Actually I working on a website where user can add his business. And I want to give him a functionality to add any location on a map. As he saves his business details along with that map details should go to database so that after posting his business on website it should show that location on a map. In short, I want to allow the user to add his location on a map and on a website for that specific user map should show his location on a map.
As I am new to all this I am getting confused how to do this. So please help me out. I searched for it on google but I am not getting any help for my problem.
Thanks in advance....
Here is my tried code:
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas, #map_canvas {
height: 400px;
width: 900px;
}
#media print {
#map-canvas, #map_canvas {
height: 400px;
width: 900px;
}
}
</style>
</head>
<body>
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: function.map.php
* Type: map
* Name: Map
* Purpose: Accept the keyword & find it on a map.
* -------------------------------------------------------------
*/
function smarty_function_map($params, &$smarty)
{
?>
<div id="panel">
<label>Location/Area*</label><input id="searchTextField" type="text" size="50" placeholder="Enter Location/Area">
<input type="text" id="city2" name="city2" />
<input type="text" id="cityLat" name="cityLat" />
<input type="text" id="cityLng" name="cityLng" />
</div>
<div id="map-canvas"></div>
<?php
}
?>
</body>
</html>
To allow users to add a marker to the map by clicking on it, you'll need to setup an event listener that will listen for any clicks on the map. Example:
var marker;
google.maps.event.addListener(map, 'click', function(event) {
if ( marker ) {
marker.setPosition(event.latLng);
} else {
marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable:true
});
}
});
You'll also want to enable the user to drag the marker after they've plotted it. You can do this by setting the marker to draggable (I did this in the above example). You'll also need to listen for any changes by attaching an event listener to the marker in question:
google.maps.event.addListener(marker, 'dragend', function(){
//Do something because marker has been dragged somewhere...
});
Finally, every time the map is clicked or a marker is dragged, you'll need to save the resulting latitude and longitude values in a hidden field(s) so that you can save the position in your database.

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