Ajax jquery not being able to pass parameters - javascript

I am trying to make a mashup application that gets json output from a restful webservice. the mashup application fetches latitude and longitude data from json response and then points it in an embedded good map.
<html>
<form>
Post Code:<br>
<input type="text" id="postcode"><br>
<button onclick="getdata()">Submit</button>
</form>
<h1>Location on Google Map</h1>
<div id="map" style="width:400px;height:400px;background:yellow"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getdata() {
var value1 = $("input#postcode").val();
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:8080/getlocation?postcode=" + value1,
"type": "POST",
"method": "GET"
}
$.ajax(settings).done(function(response) {
data = JSON.parse(response);
console.log(data['4000']['Latitude']);
var lat = data['4000']['Latitude'];
var lng = data['4000']['Longitude'];
init(lat, lng);
});
function init(lat, lng) {
latlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 20,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var customMarker = new google.maps.Marker({
position: latlng,
map: map,
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=getdata"></script>
</html>
However I am unable to pass different values to the parameters 'postcode' in
"http://localhost:8080/getlocation?postcode=". The values passed should be like 4010,4011 etc

I think its because your <script src="https://maps.googleapis.com/maps/api/js?callback=getdata"></script> is being initiated AFTER your custom script. The google maps api should be declared BEFORE your code. Place it above your <script> tags containing the custom code

Related

pass data from jQuery ajax GET request to google maps script

I have created an API that returns a json consisting of a latitude and longitude, and wanted to pass that into the Google Maps API, to get the corresponding map.
To get the data from my API I created an ajax request as follows:
scripts.js:
$(document).ready(function(){
$("button").click(function(){
$.get("my url", function(data, status){
//do something with this data
});
});
});
After I get the JSON from this, I want to pass the latitude and longitude to the script that Google Maps API provides as follows, inside my index.html.
index.html
<body>
<h1> JOS Map App </h1>
<button>Send an HTTP GET request to a page and get the result back</button>
<script type="text/javascript" src = "js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src = "js/scripts.js"></script>
<div id="map"></div>
<script> //THIS ONE!!
function initMap() {
var uluru = {lat: , lng: };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
Basically, I want to be able to pass the latitude and longitude from my GET request to this script so that I can pass them into the google maps API call. I am fairly new to jQuery, so have no idea how to do this.
Thanks!
Why not just pass the lat/lng as parameters to the Google Maps init()?
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("my url", function(data, status){
initMap(data.lat, data.lng);
});
});
});
function initMap(lat, lng) {
var uluru = {lat: lat, lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
You can move that initMap() function to scripts.js. Just make sure you're loading Google Maps API before your scripts.js.

How to specify location in google map?

I want to specify location in google map, I have javascript codes work fine but I do know how I can specify location from php variable
Below are sample codes.
<html>
<head>
<title></title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqgya6hvq6zu3Z2xeT5xEGPPi5pY2ize4&callback=initMap"></script>
</head>
<body>
<?php
//I want to search this location in google map
$location="Kigali Rwanda";
?>
<script>
var myMap;
var myLatlng = new google.maps.LatLng(52.518903284520796,-1.450427753967233);
function initialize() {
var mapOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP ,
scrollwheel: false
}
myMap = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: myMap,
title: 'Name Of Business',
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map" style="width:500px; height: 500px;">
</div>
</body>
</html>
Please anyone can help me
You can use Geocoding service in this case
function initMap() {
//var address = '<?php echo $location ?>';
var address = 'Kigali Rwanda';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
}
#map {
height: 400px;
width: 100%;
}
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
you have to use lat, lng to specifiy location. In case of country or state name you should get lat, lng of the location and define it in the code. insert the value of php variable in hidden input field. On running script get the value and process it.

How to make input type value as session variable without submit button in php

I want to get the latitude and longitude of a particular place when selected from the drop down. I found the following code online and its working fine. But I want to make this latitude and longitude as SESSION VARIABLE in order to use it in further pages. The code as follows,
index.php
<!doctyp html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Get Latitude and Longitude</title>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyBygc-IYrYq3hz2Sy_1LoKFBxwDn7U_8iw&sensor=false&libraries=places&region=uk&language=en&sensor=true">
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
Address:
<input id="searchTextField" type="text" size="50" style="text-align: left;width:357px;direction: ltr;">
<br><br>
latitude:<input name="latitude" class="MapLat" value="" type="text" placeholder="Latitude" style="width: 161px;" disabled>
longitude:<input name="longitude" class="MapLon" value="" type="text" placeholder="Longitude" style="width: 161px;" disabled>
<div id="map_canvas" style="height: 350px;width: 500px;margin: 0.6em;"></div>
<script>
$(function () {
var lat = 44.88623409320778,
lng = -87.86480712897173,
latlng = new google.maps.LatLng(lat, lng),
image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';
//zoomControl: true,
//zoomControlOptions: google.maps.ZoomControlStyle.LARGE,
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_left
}
},
map = new google.maps.Map(('map_canvas'), mapOptions),
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, {
types: ["geocode"]
});
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(autocomplete, 'place_changed', function (event) {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
moveMarker(place.name, place.geometry.location);
$('.MapLat').val(place.geometry.location.lat());
$('.MapLon').val(place.geometry.location.lng());
});
google.maps.event.addListener(map, 'click', function (event) {
$('.MapLat').val(event.latLng.lat());
$('.MapLon').val(event.latLng.lng());
infowindow.close();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"latLng":event.latLng
}, function (results, status) {
console.log(results, status);
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
moveMarker(placeName, latlng);
$("#searchTextField").val(results[0].formatted_address);
}
});
});
function moveMarker(placeName, latlng) {
marker.setIcon(image);
marker.setPosition(latlng);
infowindow.setContent(placeName);
//infowindow.open(map, marker);
}
});
</script>
</body>
</html>
I don't want to use SUBMIT BUTTON or OK BUTTON in this process. Without any button click i want to make the latitude and longitude values as SESSION VARIABLE.
Please help me out. Thanks in regards.
var lat = '44.88623409320778';
var lng = '-87.86480712897173';
$.ajax({
url: "script.php",
type: "POST",
data: { lat: lat, lng: lng }
}).done( function( msg ) {
// Complete
})
}).fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus + " - Please try again.")
})
PHP script
$_SESSION[ 'lat' ] = $_POST[ 'lat' ];
Using ajax send the lat and lng across to the php script, get the script to store it as a session variable.
You will need jquery to complete this.
After getting latitude and longitude values just store them in session variables, by starting a session. Already you are storing values in javascript variable from that store the values in a session.

Google map v2 to v3 code

I am working on a migration project from google maps V2 to V3 and wrote the bellow code but
getting error and unable to solve the problem.
Am i using wrong method of google maps?
What is wrong in this code?
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='. $mapKey .'&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( $_ADDRESS );
// initialize map
function initialize()
{
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.getPosition( address, function(point)
{
if (!point)
{
alert(address + " not found");
}
else
{
map.setCenter(point, 13);
var marker = new google.maps.Marker(point);
map.addOverlay(marker);
//marker.openInfoWindowHtml(address);
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Any idesa?
Thanks
I have split these answers as the first deals with the fundamentals of the javascript, this then deals with using the Google Maps API.
As I've never used the maps API, I can't comment on V2, but looking at how you do things in V3, I think this does what you're looking for...
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( "$_ADDRESS" );
// initialize map
function initialize( address )
{
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.geocode( { "address": address }, function( results, status )
{
if ( status == google.maps.GeocoderStatus.OK )
{
position = results[0].geometry.location;
map.setCenter(position, 13);
var marker = new google.maps.Marker({ map: map, position: position });
}
else
{
alert(address + " not found");
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Having said that, I'd question the str_replace straight into the javascript - can you trust the source of that data? If not, then you should look up how to sanitise that string before you put it into your javascript or you may allow people to inject code into your site.
Looking at the fundamental javascript issues you have...
Try adding quotes around the string that you're replacing into the javascript
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
Becomes:
echo $map = str_replace('$_ADDRESS', "'MYADDRESS'", $map );
That way the string that contains the address in javascript is properly quoted.
Also, ensure that you can receive the address in your initialize function:
function initialize()
Becomes:
function initialize( address )
Finally, do not redeclare "map" when you assign it a value in "initialize", otherwise you are referencing a different variable that only exists in that function:
var map = new google.maps.Map(document.getElementById("map_canvas"), {
Becomes:
map = new google.maps.Map(document.getElementById("map_canvas"), {

Error with "new google.maps.directionService()" on google maps api

I'm tryng to do a map with google maps api and jquery-mobile, the map I want to do it's a directions map. I've two GPS coordinate and I wanto to show the way betwen the two points when the map is initialized. This is the code:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="../js/jquery.ui.map.js"></script>
<script type="text/javascript" src="../js/jquery.ui.map.extensions.js"></script>
and the code of the script is:
<script type="text/javascript" >
var dirService;
var render;
function calcolateRoute(){
dirService = new google.maps.directionService();
var myOrigin = new google.maps.LatLng( 46.448327,12.37707);
var myDestination = new google.maps.LatLng( 46.443993,12.388498)
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myOrigin};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var renderOpt = { map:map };
render = new google.maps.directionRenderer(renderOpt);
var requestRoute = {
origin: myOrigin,
destination: myDestination,
travelMode: google.maps.travelMode.BICYCLING};
dirService.route(requestRoute, function(result, status){
if(status == google.maps.DirectionsStatus.OK){
render.setDirection(result);
}else{
alert('ERROR ');}
});
}
</script>
When the browser render the page i receive this error:
Uncaught TypeError: undefined is not a function
at the line
dirService = new google.maps.directionService();
I don't understand why the script return the error.... Someone can help me?
Sorry for my bad english!!
You are spelling the DirectionsService incorrectly
Should be:
dirService = new google.maps.directionsService();
Not:
dirService = new google.maps.directionService();

Categories