I found a script on google maps api page where user can select location and send data to PHP -> MySQL. It works fine in chrome and IE, but when i try to save location in mozilla, all it does is refresh parent page.
I'm pretty much clueless when it comes to javascript, so if anyone can find error, would appreciate it :)
Code
<!DOCTYPE html >
<head>
<meta name=viewport content='initial-scale=1.0, user-scalable=no' />
<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<script type='text/javascript' src='https://maps.googleapis.com/maps/api/js'></script>
<script type='text/javascript'>
var marker;
var infowindow;
function initialize() {
var latlng = new google.maps.LatLng(33.137550, -42.187500);
var options = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), options);
var html = "<table><tr><td><input type='button' value='Save Location' onclick='saveData(), window.parent.location.reload();'/></td></tr></table>";
infowindow = new google.maps.InfoWindow({
content: html
});
function addMarker(location) {
if (!marker) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
else { marker.setPosition(location); }
}
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
}
function saveData() {
var latlng = marker.getPosition();
var url = 'insert_location.php?lat=' + latlng.lat() + '&lng=' + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length >= 1) {
infowindow.close();
}
});
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body style='margin:0px; padding:0px;' onload='initialize()'>
<div id='map-canvas' style='width: 100%; height: 800px'></div>
<div id='message'></div>
</body>
</html>
Javascript isn't off by default, but maybe yours is turned off.
If you want to turn Javascript on, please do the following:
Type about:support into your address bar, press Enter
Accept the warning
Search for javascript.enabled
Make sure the value is true. (Double click it if it is not)
And statements like this - "I'm pretty much clueless when it comes to javascript" aren't going to help you. Put some effort into it and research before you come here asking for the rest of us to solve your issue for you.
Related
I am working on creating a page using html and javascript.
I have json file that proves inputs to some of the contents i need.
What Im trying to do is to have address variable setup so that google map API can be displayed on my page.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address = cmpyJson[jobCmpyID].company_name+" Company, "+locJson[jobLocID].location_name;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:200px;"></div>
</body>
</html>
above is part of the code.
the address variable has to look like
var address= "google Company, Austin, TX"
for google to recognize it properly.
if i know for fact that json returns exactly what im asking, what could be the problem here? how could i go about fixing it?
updated to ease some confusions.
when i view the source code on my website, i see that returned values are strings...
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address =Oracle+" Company, "+San Francisco, CA;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:200px;"></div>
</body>
assuming that all of these variables exist, the following line should be:
var address = cmpyJson[jobCmpyID].company_name+" Company, "+locJson[jobLocID].location_name;
I just removed all of the curly brackets to make it syntactically correct.
If address is supposed to produce a string, and pull in parts from the cmpJson object, then do this:
var address =cmpyJson[jobCmpyID].company_name +" Company, "+
locJson[jobLocID].location_name;
You don't need the {{ }} around the JSON object references. Also, if you plan to pass this into google, you need to encode it.
I have a website that loads 3 seperate "views" of a location via Google Maps, Street and Places.
Please see my code below:
I have finally gotten Maps and Street view to work properly but am struggling a bit with this one.
I have a tab that displays the same as map but with places added.
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
<script type="text/javascript">
var myLattitude = <?php echo $data["lattitude"]; ?>;
var myLongitude = <?php echo $data["longitude"]; ?>;
var poiMap;
var infowindow;
function initializePoi() {
var poiCentre = new google.maps.LatLng(myLattitude, myLongitude);
poiMap = new google.maps.Map(document.getElementById('poi-canvas'), {
center: poiCentre,
zoom: 15
});
var request = {
location: poiCentre,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(poiMap);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: poiMap,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(poiMap, this);
});
}
Now This initializes properly but the console throws the following error:
TypeError: google.maps.places is undefined
I just want to know why I get this error, I like having clean errorless code.
The places do actually show up properly and everything.
You should add the option libraries=places in the Google API URL
In your case you should replace the following:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
With this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Look at the end of the src=""
Now, you have to use https instead of http.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Everything else is same as previous answer mentioned.
Since the top answer addresses the vanilla version, this is for those using google-maps-react:
add libraries: ['places'] to your GoogleMapReact Component:
<GoogleMapReact
bootstrapURLKeys={{ key: apiKey, libraries: ['places'] }}
...
/>
If you are using React.
import { Wrapper as MapsWrapper } from "#googlemaps/react-wrapper";
// Note libraries prop.
<MapsWrapper apiKey={'YOUR_API_KEY'} libraries={['places']}>
<ChildComponent />
</MapsWrapper>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Ok, I'm using the Google Maps API and I need to convert my users location they enter, convert it to Latitude/Longitude using the API. So far, I just have some PHP, But i'm not sure how to implement this into the javascript, etc.
<?php
$coords = toCoordinates("88 Main St. New York New York USA");
function toCoordinates($address)
{
$bad = array(
" " => "+",
"," => "",
"?" => "",
"&" => "",
"=" => ""
);
$address = str_replace(array_keys($bad), array_values($bad), $address);
$data = new SimpleXMLElement(file_get_contents("http://maps.google.com/maps/geo?output=xml&q={$address}"));
$coordinates = explode(",", $data->Response->Placemark->Point->coordinates);
return array(
"latitude" => $coordinates[0],
"longitude" => $coordinates[1]
);
}
?>
Thank you!
first you have to create the xml and after that pass the xml to the javascript stated below
<?xml version="1.0" encoding="UTF-8"?>
<markers>
<marker Company_Name="Company Name" address="Address" lat="39.74259" lng="-104.98359" type="comp"/>
<marker Company_Name="Company Name" address="Address" lat="39.6823891" lng="-104.9373677" type="comp"/>
</markers>
<script src="https://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
comp: {
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=<?php echo $allcompanyaddress[8];?>|FF0000|000000',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
};
function myload() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?php echo $info['latitude']; ?>, <?php echo $info['longitude'];?>),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
// downloadUrl("<?php echo base_url();?>user_jobplacement/googlemap_record/'", function(data) {
downloadUrl("URL of your XML", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("Company_Name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var broker = markers[i].getAttribute("broker");
var phone = markers[i].getAttribute("phone");
var paid = markers[i].getAttribute("paid");
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'mouseover', 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() {}
window.onload = myload;
//]]>
</script>
<div id="map" style="width: 500px; height: 338px"></div>
Have you tried using JQuery for that? You simply need to use GET with parameters(address in your case) like this:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.get(
"http://maps.googleapis.com/maps/api/geocode/json?address=88 Main St. New York New York USA&sensor=true",
function(data) {
console.log(data);
}
);
});
</script>
</head>
</html>
In return you get all the content in data variable(object) from which you can simply extract the latitude and longitude. For your case change the address in URL to value entered by user.
I want your guys' help on this. I wrote the code for allowing users to create markers(with infowindow) with a 'click' function that will save the lat/lan and other info to a MySQL database that will then be called to show the markers on the map. When you click on the map, it creates a marker but it will not save the info in the infowindow to the database. I followed the guide from the google maps developer's guide but I still can't get it to work. I even triple checked to make sure my MySQL login details work correct and still nothing.
Here is the code to the map itself:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js? sensor=false"></script>
<script type="text/javascript">
var marker;
var infowindow;
function initialize() {
var latlng = new google.maps.LatLng(37.4419, -122.1419);
var options = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
var html = "<table>" +
"<tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>" +
"<tr><td>Address:</td> <td><input type='text' id='address'/></td> </tr>" +
"<tr><td>Type:</td> <td><select id='type'>" +
"<option value='bar' SELECTED>bar</option>" +
"<option value='restaurant'>restaurant</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
}
function saveData() {
var name = escape(document.getElementById("name").value);
var address = escape(document.getElementById("address").value);
var type = document.getElementById("type").value;
var latlng = marker.getPosition();
var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
"&type=" + type + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
document.getElementById("message").innerHTML = "Location added.";
}
});
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map-canvas" style="width: 500px; height: 300px"></div>
<div id="message"></div>
</body>
</html>
This is what is supposed to save info to the database(phpsqlinfo_addrow.php):
<?php
require("phpsqlinfo_dbinfo.php");
// Gets data from URL parameters
$name = $_GET['name'];
$address = $_GET['address'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$type = $_GET['type'];
// Opens a connection to a MySQL server
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = sprintf("INSERT INTO markers " .
" (id, name, address, lat, lng, type ) " .
" VALUES (NULL, '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($name),
mysql_real_escape_string($address),
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($type));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
hi i have same issue with my project to save customer location,
which they click on there browser,
what i did was i save location in latitude and longitude in two input box as{you may take it hidden so it will not seen} in and give submit button and submit form i have given code you can also change it to submit form on click on map by submitting form on click by this and you can also store latitude and longitude in same column if you want
and you will need to insert you key
document.getElementById("yourform").submit();
<html>
<head>
<style type="text/css">
#map_canvas {height:300px;width:500px}
</style>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=""""youerapikeyhere""""&language=mr"></script>
<script type="text/javascript">
var map;
var marker;
var markersArray = [];
function initialize()
{
var latlng = new google.maps.LatLng(18.5236, 73.8478);
var mapOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
if (marker) {
marker.setMap(null); //code
}
//adding marker
document.getElementById('txtLat').value=event.latLng.lat();
document.getElementById('txtLng').value=event.latLng.lng();
marker= new google.maps.Marker({
position: event.latLng,
map: map,
title: 'pune'
});
//creting info window instance
var infowindow = new google.maps.InfoWindow({
content: 'selected location'
});
//adding pointer click event to open infowindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<table cellpadding="0" cellspacing="0">
<tr><td colspan=3><div id="map_canvas" style="background-color: #ffffff"></div></td></tr>
<tr><td><input type="text" id="txtLat" name="txtLat"style="width:150px"></td>
<td><input type="text" id="txtLng" name="txtLng"style="width:150px"></td></tr>
</table></form>
</html>`
Try to narrow down the possibilities, or at least find out "where" it went wrong; meaning, is the issue caused from the front end or in the backend!?
If you use Webkit UA (browser) or its variants, use its Developer tools; if using Firefox, install an AddOn called FireBug. In the marker's click handler, try to output the coordinates using alert() or console.log() and see if the results are accurately fetched. Next check whether the AJAX call is passed as it should be to the backend.
In your PHP, try to examine the incoming values (from request parameters). Also turn on the debug output in php.ini so you'll know if the DB connections are successfully made by checking stderr or system logs.
There's a lot of things that could go wrong. It's hard to tell given by the lack of details you provided, but I hope my reply helps you to get a good start.
Oh, BTW, I'd strongly suggest you switch to PDO over mysql_, the mysql_ are to be deprecated in the future.
a while back someone from stackoverflow helped me come with a nice solution to using google maps api on 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 geocoder;
var map;
function initialize(address) {
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Flordia")}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Windows application code
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
WebBrowser1.Document.InvokeScript("initialize", New String() {AddressM.Text})
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Url = New Uri("http://datasharesas.com/CompanyAdmin/map2.html")
End Sub
End Class
image of the project
now the issue is that when i look the same address once, it works perfectly.
when i search it twice i get a grey screen and when i search more than 3 times i get an error script
error message
how can this be fixed ?
thank you in advance,
Leo P.
Geocoding is asynchronous, so in some cases, (depending on how fast it returns), your map is not yet created when you try to use it. You need to create the map first and geocode afterwrds. Try this instead:
script type="text/javascript">
// Global vars
// Sorry, I can't be bothered typing "google.maps." every time. ;-)
var G = google.maps;
var map;
var geocoder = new G.Geocoder();
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 4,
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);
var marker = new G.Marker({
map: map,
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>