Passing latitude and longitude as parameters in url - javascript

I am trying to create an html file to show google maps. Here is the code I am using to accomplish it.
<!DOCTYPE html>
<html>
<head>
<title> Map</title>
</head>
<body>
<div id="map-container" class="col-md-6"></div>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
function init_map() {
var var_location = new google.maps.LatLng(12.989802,80.2487);
var var_mapoptions = {
center: var_location,
zoom: 14
};
var var_marker = new google.maps.Marker({
position: var_location,
map: var_map,
title:"Venice"});
var var_map = new google.maps.Map(document.getElementById("map-container"),
var_mapoptions);
var_marker.setMap(var_map);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
</body>
In this code the values and latitude and longitude are manually given inside the js. But i want that latitude and longitude to be passed as url parameters.
EX : http://www.smart.com/3.html?q=12.989802,80.2487
This is because my url will be called from an app and they want to pass latitude and longitude as a parameters.

You can write code to read and parse the query string. One description of how to do that is Part 20 Passing and receiving parameters of Mike Williams' Google Maps Javascript API v2 tutorial (note that v2 is deprecated and turned off, but the same principles apply to v3).
example using "q=40.7127837,-74.0059413" (the code snippet doesn't take query parameters)
function init_map() {
var lat, lng;
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?q=42,-72"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q") {
var coords = value.split(",");
lat = parseFloat(coords[0]);
lng = parseFloat(coords[1]);
}
}
var var_location;
if (isNaN(lat) || isNaN(lng)) {
var_location = new google.maps.LatLng(12.989802, 80.2487);
} else {
var_location = new google.maps.LatLng(lat, lng);
}
var var_mapoptions = {
center: var_location,
zoom: 14
};
var var_marker = new google.maps.Marker({
position: var_location,
map: var_map,
title: "Venice"
});
var var_map = new google.maps.Map(document.getElementById("map-container"),
var_mapoptions);
var_marker.setMap(var_map);
}
google.maps.event.addDomListener(window, 'load', init_map);
html,
body,
#map-container {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-container" class="col-md-6"></div>

I edited your function. Try this.
function init_map() {
var urlParams = /\?q=([^,]+),([^,]+)/.exec(window.location.search),
var_location;
if (urlParams) {
var_location = new google.maps.LatLng(parseFloat(urlParams[1]), parseFloat(urlParams[2]));
} else {
return;
}
var var_mapoptions = {
center: var_location,
zoom: 14
};
var var_marker = new google.maps.Marker({
position: var_location,
map: var_map,
title: "Venice"
});
var var_map = new google.maps.Map(document.getElementById("map-container"),
var_mapoptions);
var_marker.setMap(var_map);
}
Is this the behaviour you want? Just bear in the mind. If there are no required parameters in the url function will do nothing. Make sure to put any default or doing anything else. Good luck in implementation.

Related

condition not working properly in google map javaScript for marker

I am trying to plot different markers on google maps taking data from a csv file. I am using parsecsv-0.4.3-beta to read the csv. Everything is working just fine except when I compare two fields and try to change the marker according to that. It is changing the marker but for few fields it's giving the wrong marker. I think I have made some mistake in the condition.
<?php
# include parseCSV class.
require_once('../parsecsv.lib.php');
# create new parseCSV object.
$csv = new parseCSV();
# Parse '_books.csv' using automatic delimiter detection...
$csv->auto('latlang.csv');
# ...or if you know the delimiter, set the delimiter character
# if its not the default comma...
// $csv->delimiter = "\t"; # tab delimited
# ...and then use the parse() function.
// $csv->parse('_books.csv');
//print_r ($csv->data);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCWPvg5SpuPqRnY0Ldhlz2QhLgrCqnlYFM&sensor=false"></script>
<script type="text/javascript">
var markers = <?php print json_encode($csv->data); ?>;
window.onload = function () {
LoadMap();
}
function LoadMap() {
var mapOptions = {
center: new google.maps.LatLng(markers[1].Latitude, markers[1].Longtitude),
zoom: 7,
styles: [{"stylers": [{ "saturation": -100 }]}],
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
//Create and open InfoWindow.
var infoWindow = new google.maps.InfoWindow();
for (var i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.Latitude, data.Longtitude);
var image1 = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
var image2 = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
**if (data.CL < data.DL) {
var image = image2;
}else {
var image = image1;
};**
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.Station,
icon:image,
});
//Attach click event to the marker.
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
//Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + "<p>" + "<b>Station:</b> " + data.Station + "<br>"+ "CL:" + data.CL + "<br>" + "<b>River Name: </b>" + data.RiverName + "<br>" + "<b>DL(mPWD): </b>" + data.DL +"<br>" + "<b>HRWL(mPWD):</b> "+ data.HRWL +"</p>"+"</div>");
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
<div id="dvMap" style="width: 900px; height: 500px">
</div>
</body>
</html>
Here is a sample of the csv file:
In most cases it shows the right marker... some markers do not meet the condition.
Please add these lines in your code:
data.CL = Number(data.CL);
data.DL = Number(data.DL);
if (data.CL < data.DL) {
var image = image2;
}else {
var image = image1;
};
Your data was coming in string, but we are using < operator to check that so in some case it might fail. Better to convert and then check for greater or less.

Autozoom / Autocenter with GoogleMaps Avi v3 JS

I'm writing a code in order to display some pushpins on a maps, using Google Maps V3 APi (JS).
I would like to use Autozoom and Autocenter.
For this, i need to use Bound.extends() and map.fitBounds(), nevertheless, with the use of this functions i have only one pushpins...not the other...it's very strange...
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 768px"></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
// A function to create the marker and set up the event window
function createMarker(point,name)
{
var marker = new google.maps.Marker({position: point, title: name});
google.maps.event.addListener(marker, "click", function(){
marker.openInfoWindowHtml(name);});
return marker;
}
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'));//, { center: {lat: -34.397, lng: 150.644},zoom: 8});
var geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), optionsCarte);
var bounds = new google.maps.LatLngBounds();
// ========== Read paramaters that have been passed in ==========
// If there are any parameters at the end of the URL, they will be in location.search
// looking something like "?q=My+First+Point#59.591,17.82"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++)
{
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q")
{
var text = unescape(value);
var parts = text.split("#");
geocoder.geocode( { 'address': parts[1]}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);//center the map over the result
var title = parts[0];
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
bounds.extend(results[0].geometry.location);
}
}
map.fitBounds(bounds)
map.panToBounds(bounds);
map.setCenter(bounds.getCenter());
}
</script>
In order to execute my call, i have to do this :
http://XX.XX.XX.XX/MutliMaps.html?q=MyPushPin1#myAdresse1&q=MyPushPin2#myAdresse2
Any idea where is my error? I think it's the bound.extend fonction.
You must move the code related to the bound, zoom and center inside the loop
so you first you have geocode result available (and so you don't get the error for this ) and second you can extend the bound incrementally ..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 768px"></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
// A function to create the marker and set up the event window
function createMarker(point,name)
{
var marker = new google.maps.Marker({position: point, title: name});
google.maps.event.addListener(marker, "click", function(){
marker.openInfoWindowHtml(name);});
return marker;
}
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'));//, { center: {lat: -34.397, lng: 150.644},zoom: 8});
var geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), optionsCarte);
var bounds = new google.maps.LatLngBounds();
// ========== Read paramaters that have been passed in ==========
// If there are any parameters at the end of the URL, they will be in location.search
// looking something like "?q=My+First+Point#59.591,17.82"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++)
{
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q")
{
var text = unescape(value);
var parts = text.split("#");
geocoder.geocode( { 'address': parts[1]}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);//center the map over the result
var title = parts[0];
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location});
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds)
map.panToBounds(bounds);
map.setCenter(bounds.getCenter());
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
//bounds.extend(results[0].geometry.location);
}
}
//map.fitBounds(bounds)
///map.panToBounds(bounds);
//map.setCenter(bounds.getCenter());
}
</script>

map don't display with googlemaps js API

I'm tryin to use a sample code in order to have a webpage in order to display multiples pushpin on the map.
Here is my html code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" style="width: 1024px; height: 768px"></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
// A function to create the marker and set up the event window
function createMarker(point,name)
{
var marker = new google.maps.Marker({position: point, title: name});
google.maps.event.addListener(marker, "click", function(){
marker.openInfoWindowHtml(name);});
return marker;
}
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'));//, { center: {lat: -34.397, lng: 150.644},zoom: 8});
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), optionsCarte);
var bounds = new google.maps.LatLngBounds();
// ========== Read paramaters that have been passed in ==========
// If there are any parameters at the end of the URL, they will be in location.search
// looking something like "?q=My+First+Point#59.591,17.82"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++)
{
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q")
{
var text = unescape(value);
var parts = text.split("#");
var latlng = parts[1].split(",");
var point = new google.maps.LatLng(parseFloat(latlng[0]),parseFloat(latlng[1]));
var title = parts[0];
var marker = createMarker(point,title);
marker.setMap(map);
bounds.extend(point);
}
}
//map.setZoom(map.getBoundsZoomLevel(bounds));
map.fitBounds(bounds)
map.setCenter(bounds.getCenter());
}
</script>
The trick is to use the url with parameters in order to add locations to display :
Ex: http://myserver.com?q=MyFirstPoint#59.591,17.82
Actually nothing is displayed..
Anyone can help me please ? My API key is on the code ;)
Thanks a lot,
Best regards,
Fab'
You have a
callback=initMap
but I see no function by this name
and similar you have
<body onunload="GUnload()">
but I see no function by this name
You must be suure you call the proper init function for display the maps and check in browser console for other errors
?q=MyFirstPoint#59.591,17.82&q=MyLastPoint#54.591,12.82
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="map" style="width: 550px; height: 450px"></div>
<script>
(function (myGoogleMap) {
var map;
var latLngBounds;
myGoogleMap.init = function () {
console.log('init');
latLngBounds = new google.maps.LatLngBounds();
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN,
panControl: false,
zoomControl: true,
mapTypeControl: true,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
});
getData();
};
function getData() {
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0, l = pairs.length; i < l; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1);
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "q") {
var text = decodeURI(value);
var parts = text.split("#");
var latlng = parts[1].split(",");
setMarker(parseFloat(latlng[0]), parseFloat(latlng[1]), parts[0]);
}
}
centerMap();
}
function setMarker(lat, lng, contentString) {
var latLng = new google.maps.LatLng(lat, lng);
latLngBounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}
function centerMap() {
map.fitBounds(latLngBounds);
}
}(window.myGoogleMap = {}))
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=myGoogleMap.init"></script>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
</body>
</html>
I hope this could help.

How do I add this jQuery into my Javascript?

I'm extremely new to both JS and jQuery, and I've got this code:
<html>
<style>
/**
* Default attributes for gadget body.
*/
body {
font-family: Arial;
background: none transparent;
padding: 0px;
}
html, body, #map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<body>
<div id="map_canvas"></div>
<script>
var APIKey = "MyKeyValueIsInHere";
var geocoder;
var map;
var marker;
var locationTest = 'http://nominatim.openstreetmap.org/reverse?format=json&lat=55.653363&lon=12.547604&zoom=18&addressdetails=1';
var lat = 55.653363;
var lng = 12.547604;
function initialize() {
var latlng = new google.maps.LatLng(lat,lng);
// set the options for zoom level and map type
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// create a map in the map_canvas div element
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.setCenter(latlng);
var marker = new google.maps.Marker({
map: map,
position: latlng
});
alert(locationTest);
var text = JSON.parse(locationTest);
var infoWindow = new google.maps.InfoWindow();
var houseNumber = text.address.house_number;
var road = text.address.road;
var suburb = text.address.suburb;
var zipCode = text.address.postcode;
var city = text.address.city;
var address = road + " " + houseNumber + ", " + zipCode + " " + suburb + " i " + city;
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(address);
infoWindow.open(map, this);
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=" + APIKey + "&sensor=false&callback=initialize";
document.body.appendChild(script);
}
loadScript();
</script>
</body>
</html>
And i need to incorporate the following code :
$('#c').load('http://nominatim.openstreetmap.org/reverse?format=json&lat=55.653363&lon=12.547604&zoom=18&addressdetails=1', function (response) {
console.log('response is', response);
var b = $('#c').html();
console.log('b is', b);
var a = JSON.parse(b);
console.log('a is ', a);
$('#d').html(a.address.neighbourhood);
});
Basically, this code is supposed to show a location on google maps, the location is set by long and latitude. On the marker, I want an info box to pop up with the address. The jQuery code i've found, seems to work here, but I have fallen short now that I have to include it into my JS. I hope someone can help me, I can't figure out how to implement it.
You need to add jquery script link to your tag.
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>

How do I use Google Maps geocoder.getLatLng() and store its result in a database?

Hey everybody! Im trying to use getLatLng() to geocode a list of postal/zip codes and store the generated point in the database to be placed on a map later. This is what I've got so far:
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var serializedPoint = $.param(point);
//Geocode(id, point);
}
});
});
function Geocode(id, point) {
alert(point);
$.post("/Demographic/Geocode/" + id, point, function () {
alert("success?");
});
}
but I'm getting this.lat is not a function in my error console when i try to serialize the point object or use it in $.post()
From my research, I understand that geocoder.getLatLng() is asynchronous, how would that affect what I'm trying to do? I'm not running this code in a loop, and I'm trying to post the point using the anonymous callback function.
How can I save the information from point to use later?
Update
Creating a marker and trying to post that still results in the this.lat is not a function in the error console.
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var marker = new GMarker(point);
$.post("/Demographic/Geocode/" + id, marker, function () {
alert("success?");
});
}
});
});
** Another Update **
I really need to save the geocoded address for later, even if I store the latitude/longitude values in my database and remake the marker when I'm ready to put it onto a map. Again, serializing or posting - seemingly using the point in any way other than in google maps functions gives the this.lat is not a function exception in my error log.
I'm using asp.net mvc - are there any frameworks out there that would make this easier? I really need help with this. Thanks.
If your stuck for 2 days maybe a fresh v3 start would be a good thing, this snipped does a similair job for me...
function GetLocation(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
ParseLocation(results[0].geometry.location);
}
else
alert('error: ' + status);
});
}
}
function ParseLocation(location) {
var lat = location.lat().toString().substr(0, 12);
var lng = location.lng().toString().substr(0, 12);
//use $.get to save the lat lng in the database
$.get('MatchLatLang.ashx?action=setlatlong&lat=' + lat + '&lng=' + lng,
function (data) {
// fill textboss (feedback purposes only)
//with the found and saved lat lng values
$('#tbxlat').val(lat);
$('#tbxlng').val(lng);
$('#spnstatus').text(data);
});
}
Have you tried this?
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var marker = new GMarker(point);
map.addOverlay(marker);
obj = {lat: marker.position.lat(),
lng: marker.position.lng()};
$.post("/Demographic/Geocode/" + id, obj, function () {
alert("success?");
});
}
});
});
I haven't used V2 in a long time, so I'm not sure about the exact syntax, but the point is to create an object from the information you need (lat/lng) and serialize that.
Also, an upgrade to V3 is much recommended, if plausible.
You need to set a marker on the map, which takes a lat/long. You can save that info however you want or display immediately. (Code truncated for demo purpose)
map = new google.maps.Map(document.getElementById("Map"), myOptions);
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location
});
marker.setMap(map);
}
}
UPDATE (FOR v2)
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
}
});
});
In V3 the coordinates must be first serialized as a string as shown by Arnoldiuss, before sending as json post data.
var lat = latlong.lat().toString().substr(0, 12);
var lng = latlong.lng().toString().substr(0, 12);
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<%# taglib prefix="s" uri="/struts-tags"%>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyDS1d1116agOa2pD9gpCuvRDgqMcCYcNa8&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var latitude = document.getElementById("latitude").value;
latitude = latitude.split(",");
var longitude = document.getElementById("longitude").value;
longitude = longitude.split(",");
var locName = document.getElementById("locName").value;
locName = locName.split(",");
var RoadPathCoordinates = new Array();
RoadPathCoordinates.length = locName.length;
var locations = new Array();
locations.length = locName.length;
var infowindow = new google.maps.InfoWindow();
var marker, i;
var myLatLng = new google.maps.LatLng(22.727622,75.895719);
var mapOptions = {
zoom : 16,
center : myLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//To Draw a line
for (i = 0; i < RoadPathCoordinates.length; i++)
RoadPathCoordinates[i] = new google.maps.LatLng(latitude[i],longitude[i]);
var RoadPath = new google.maps.Polyline({
path : RoadPathCoordinates,
strokeColor : "#FF0000",
strokeOpacity : 1.0,
strokeWeight : 2
});
//Adding Marker to given points
for (i = 0; i < locations.length; i++)
locations[i] = [locName[i],latitude[i],longitude[i],i+1];
for (i = 0; i < locations.length; i++)
{marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[i][1], locations[i][2]),
map : map
});
//Adding click event to show Popup Menu
var LocAddress ="";
google.maps.event.addListener(marker, 'click', (function(marker, i)
{ return function()
{
GetAddresss(i);
//infowindow.setContent(locations[i][0]);
infowindow.setContent(LocAddress);
infowindow.open(map, marker);
}
})(marker, i));}
function GetAddresss(MarkerPos){
var geocoder = null;
var latlng;
latlng = new google.maps.LatLng(latitude[MarkerPos],longitude[MarkerPos]);
LocAddress = "91, BAIKUNTHDHAAM"; //Intializing just to test
//geocoder = new GClientGeocoder(); //not working
geocoder = new google.maps.Geocoder();
geocoder.getLocations(latlng,function ()
{
alert(LocAddress);
if (!response || response.Status.code != 200) {
alert("Status Code:" + response.Status.code);
} else
{
place = response.Placemark[0];
LocAddress = place.address;
}
});
}
//Setting up path
RoadPath.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<s:form action="mapCls" namespace="/">
<s:hidden key="latitude" id="latitude"/>
<s:hidden key="longitude" id="longitude"/>
<s:hidden key="locName" id="locName"/>
<div id="map_canvas" style="float:left;width:70%;height:100%"></div>
</s:form>
</body>
</html>
I am doing reverse Geocoding, and want address of marker using lat and longitude. M facing problem with function "GetAddresss()", line "geocoder.getLocations(latlng,function ()" is not working properly. what should I Do?

Categories

Resources