I am currently working on a code where when the user enters location he will get latitude n longitude however i need to add both lat and long to database. Client side the code is working the html file is given below.
How do I transfer these values for server side in php and add them to database.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>maps</title>
<style>
#map_canvas { width:400px; height:450px; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js? sensor=false">
</script>
<script type="text/javascript">
var geocoder;
var map;
var lat;
var lng;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-30.070, -51.190);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
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);
var marker = new google.maps.Marker;
document.getElementById('lat').value = results[0].geometry.location.lat();
document.getElementById('lng').value = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<form action="map2.php" method="get">
<div id="map_canvas"></div>
<div>
<input id="address" type="textbox" value="">
<input type="button" value="Localizar!" onclick="codeAddress()"><br>
Latitude: <input type="text" id="lat"><br>
Longitude: <input type="text" id="lng"><br>
</div>
You can do this easily using jquery( no page load or form submit needed)-
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker;
document.getElementById('lat').value = results[0].geometry.location.lat();
document.getElementById('lng').value = results[0].geometry.location.lng();
// add this
var latt=results[0].geometry.location.lat();
var lngg=results[0].geometry.location.lng();
$.ajax({
url: "your-php-code-url-to-save-in-database",
dataType: 'json',
type: 'POST',
data:{ lat: lat, lng: lngg }
success: function(data)
{
//check here whether inserted or not
}
});
}
and in the php file :
<?php
// file name: your-php-code-url-to-save-in-database.php
$lat=$_POST['lat'];
$lng=$_POST['lng'];
// write your insert query here to save $lat and $lng
?>
to know more and download Jquery visit :http://jquery.com/download/
Another way is without Jquery( Page will redirect to map2.php):
<div id="map_canvas"></div>
<form action="map2.php" method="get">
<div>
<input id="address" type="textbox" value="">
<input type="button" value="Localizar!" onclick="codeAddress()"><br>
Latitude: <input name="lat" type="text" id="lat"><br>
Longitude: <input name="lng" type="text" id="lng"><br>
</div>
</form>
and in your map2.php write-
<?php
// file name: map2.php
$lat=$_GET['lat'];
$lng=$_GET['lng'];
// write your insert query here to save $lat and $lng
//get your mysql db connection ready
$sql="insert into table_name (latitude, longitude) values('".$lat."','".$lng.")";
$command=mysql_query($sql);
// close databse connection and everythig is done then redict to any page.
//check your database table to see the inserted value
?>
In your form method I would suggest to use POST instead of GET .If you made this change then in your map2.php just change GET to POST only. To know the reason of using POST visit Link 1 and Link 2
Related
I have just added bing maps and API to my in development site however I am needing some help understanding how to have my code accept live updating lat and long coordinates and have my map update the marker in regards to these values.
Currently this is what I have but part of the code was designed for google maps which I replaced the words google with Microsoft hoping for the best.
Please be gentle I am new to coding
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=release&callback=loadMapScenario' async defer></script>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 400px; height: 400px;'></div>
<script type='text/javascript'>
// Setting boundary and loading map
function loadMapScenario() {
var bounds = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(29.332823, -81.492279), new Microsoft.Maps.Location(28.435825, -81.622231));
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Bing Maps Key',
maxBounds: bounds
});
// Highlighting the border of bounds on the map
var boundsBorder = new Microsoft.Maps.Polyline([bounds.getNorthwest(),
new Microsoft.Maps.Location(bounds.getNorthwest().latitude, bounds.getSoutheast().longitude),
bounds.getSoutheast(),
new Microsoft.Maps.Location(bounds.getSoutheast().latitude, bounds.getNorthwest().longitude),
bounds.getNorthwest()], { strokeColor: 'red', strokeThickness: 2 });
map.entities.push(boundsBorder);
}
</script>
<script>
function getReverseGeocodingData(lat, lng) {
var latlng = new Microsoft.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new Microsoft.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== Microsoft.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == Microsoft.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
}
});
}
</script>
The Bing Maps V8 team actually has a documented code sample on how to do exactly this here: https://msdn.microsoft.com/en-us/library/mt712803.aspx
I want to display multiple tags on my google map based on the location from my database. I am using PHP and javascript for my map. I am at lost for the moment on how I will be able to show all the locations from my database. Could anyone please help me? I would really appreciate it. Thanks in advance!
below is my current code for my map:
<?php
$hostname = 'localhost';
$dbname = 'db'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
mysql_connect("$hostname", "$username", "$password") or DIE("Connection to host is failed, perhaps the service is down!");
mysql_select_db("$dbname") or DIE("database not available");
$loc = "N1433.704483,E12100.012501";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>DLTI Locator</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 500px;"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', latitude,longitude ],
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(14.5833, 120.9667),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
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
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
try this tutorial.. i used it to get markers from my database.. you too could do the same..
https://developers.google.com/maps/articles/phpsqlajax_v3
i've been dealing with this couple of hours and i still cant figure how to do it.
my objective is to display only one marker when searching addresses close to each other.
below you have the code i use in my html in order to search for addresses, note - i'm developing a windows application that does such, in which case you might find some missing stuff to do actions by clicking buttons since this is done via .NET windows application
html code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var geocoder = new G.Geocoder();
var marker;
var markersArray = [1];
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
reading previous posts i know that if/else statement has to be used but cant get it right.
your help is very appreciated.
Leo P.
You can add a small bit of code to the beginning of your Geocode function that will remove the previous marker before setting a new one. Try this:
function geocode(address){
if (marker) {
marker.setMap(null);
}
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
Create only one marker as a global variable and change its position as needed. Like that you also save memory because you're not creating a new marker object on each request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style>
html, body {width:100%; height:100%}
</style>
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var marker;
var geocoder = new G.Geocoder();
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
// Create a single marker, (global variable), and don't give it a position just yet.
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
});
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//Position the marker
marker.setPosition(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
I have a google map script that works, but I can't figure out how to add it to my asp.net content page. What is the proper way to add the script to the page?
see code:
<%# Page Title="Our Location" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="Location.aspx.vb" Inherits="About_Location" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
##map{ height: 100% }
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server" OnLoad="codeAddress()">
<script type= "text/javascript">
var geocoder;
var map;
var marker;
function codeAddress() {
alert("hello")
//initializes the map
//create geocoder
geocoder = new google.maps.Geocoder();
//set options for the map being created
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//create map instance and pass it the myOptions object literal
map = new google.maps.Map(document.getElementById("map"), myOptions);
//geocode to get the lat and lng points of the given address
geocoder.geocode({ 'address': 'New York, New York'}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//if geocoder finds location
//center the map on the latlng points of the given address
map.setCenter(results[0].geometry.location);
map.setOptions({ zoom: 18 });
//create marker and place it on the address
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'New York, New York'
});
}
else {
//if geocoder cannot find location, alert user
alert("Could not find location");
}
});
}
</script>
<div id="map" style="width:700px; height:400px;"></div>
</asp:Content>
Put your script in separate js file, declare it like you did with Google maps script. Then you have to call it, maybe send this "#map" div id as parameter to that script, and not hard code it in javascript.
in this case you want to do that on page load with script manager :
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowGoogleMap", "codeAddress('map');", true);
btw. for google maps you can use Google Maps server control, it's much easier to use managing maps from server side:
http://googlemap.codeplex.com/
I'm trying to make a small application that takes a city & state and geocodes that address to a lat/long location. Right now I am utilizing Google Map's API, ColdFusion, and SQL Server. Basically the city and state fields are in a database table and I want to take those locations and get marker put on a Google Map showing where they are.
This is my code to do the geocoding, and viewing the source of the page shows that it is correctly looping through my query and placing a location ("Omaha, NE") in the address field, but no marker, or map for that matter, is showing up on the page:
function codeAddress() {
<cfloop query="GetLocations">
var address = document.getElementById(<cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>).value;
if (geocoder) {
geocoder.geocode( {<cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: <cfoutput>#Trim(hometown)#,#Trim(state)#</cfoutput>
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</cfloop> }
And here is the code to initialize the map:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(42.4167,-90.4290);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Test"
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
I do have a map working that uses lat/long that was hard coded into the database table, but I want to be able to just use the city/state and convert that to a lat/long. Any suggestions or direction? Storing the lat/long in the database is also possible, but I don't know how to do that within SQL.
You may want to consider the following example:
Using the V2 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Geocoding Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
// Prepare this list from ColdFusion
var locations = [
'New York, NY',
'Los Angeles, CA',
'Chicago, IL',
'Houston, TX',
'Phoenix, AZ'
];
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder();
var index = 0;
var geocoderFunction = function () {
geocoder.getLatLng(locations[index], function (point) {
if (point) {
map.addOverlay(new GMarker(point));
}
// Call the geocoder with a 100ms delay
index++;
if (locations.length > index) {
setTimeout(geocoderFunction, 100);
}
});
}
map.setCenter(new GLatLng(38.00, -100.00), 3);
// Launch the geocoding process
geocoderFunction();
}
</script>
</body>
</html>
Using the V3 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Geocoding Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
// Prepare this list from ColdFusion
var locations = [
'New York, NY',
'Los Angeles, CA',
'Chicago, IL',
'Houston, TX',
'Phoenix, AZ'
];
var mapOpt = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: new google.maps.LatLng(38.00, -100.00),
zoom: 3
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOpt);
var geocoder = new google.maps.Geocoder();
var index = 0;
var geocoderFunction = function () {
geocoder.geocode({ 'address': locations[index] }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
// Call the geocoder with a 100ms delay
index++;
if (locations.length > index) {
setTimeout(geocoderFunction, 100);
}
});
}
// Launch the geocoding process
geocoderFunction();
</script>
</body>
</html>
All you need to do is to render the JavaScript array locations from ColdFusion, instead of using the hardcoded one in the example.
Screenshot from the above example:
You need to actually add the marker to the map using the addOverlay method:
var point = new GLatLng(...);
map.addOverlay(new GMarker(point));
You can also add instances of the Marker class to your map:
map.addOverlay(marker);
See the Map Overlays docs:
http://code.google.com/apis/maps/documentation/javascript/v2/overlays.html