So I have a field address in open.php, when a user starts to write something will fecth google addresses for auto-completion. When a user selects an address a marker is positioned on the map and lat/long fields are populated.
Now I added de possibility for the user fill the address field in a previous page, then open.php gets the address from url:
<input id="address" type="text" value="<?php echo $_GET['query']; ?>"/>
But then the JS script will not run to populate map, lat and long. How can I solve this?
(I need the possibility for the user fill the address field in a previous page, because user can enter directly on open.php)
Thank you!
Code from JS:
var geocoder;
var map;
var marker;
function initialize(){
//MAP
var latlng = new google.maps.LatLng(49.599,6.134);
var options = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
//GEOCODER
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
position: latlng,
map: map,
animation: google.maps.Animation.BOUNCE,
draggable: true
});
}
$(document).ready(function() {
initialize();
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
// geocoder.geocode( {'address': request.term }, function(results, status) {
geocoder.geocode( {'address': request.term + ', lu' }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
$("#latitude").val(ui.item.latitude);
$("#longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
});
//Add listener to marker for reverse geocoding
google.maps.event.addListener(marker, 'drag', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
}
}
});
});
});
enter code here
Try something like
$('#address').trigger('change');
Related
Good day,
I have concern about adding mark icon to my google map, so every time the user will click the location. the mark will place to the location itself.
i have here the illustration
This is my code for the click function
$('button#addresses').click(function(){
var address_href = $(this).val();
var commaPos = address_href.indexOf(',');
var coordinatesLat = parseFloat(address_href.substring(0, commaPos));
var coordinatesLong = parseFloat(address_href.substring(commaPos + 1, address_href.length));
var centerPoint = new google.maps.LatLng(coordinatesLat, coordinatesLong);
map.setCenter(centerPoint);
})
so if the user click the address the google map automatically change the location.
This is the code for default function of google map
var map;
function initMap() {
var myHome = { "lat" : "53.628301" , "long" : "-113.408736" };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(myHome.lat, myHome.long),
mapTypeId: 'roadmap'
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map)
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
icon: '{{ asset('assets/googlemap-marker-hiflyer.png') }}'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowidnow.open(map, this);
});
} else {
alert('Fill the blank');
}
});
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var features = [
{
position: new google.maps.LatLng(53.628301, -113.408736),
type: 'info'
},
];
// Create markers.
features.forEach(function(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: '{{ asset('assets/googlemap-marker-hiflyer.png') }}',
map: map
});
});
}
So the question is how to set the marker if the user click the location.
Thanks guys. I hope it will solve my problem.
I have a working Google Map on my site using Google Maps API v3.
The map is loaded on pageload and applied with multiple markers/positions from an array of coordinates.
Now, what I want to do is to dynamically update the markers/positions with a new array of coordinates with an ajax call.
Here is an example of my markup:
<div id="map-canvas"></div>
<script type="text/javascript">
var LocationData = <?php echo $coordsarray; ?>;
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
draggable: true
} );
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in LocationData)
{
var p = LocationData[i];
var latlng = new google.maps.LatLng(p[0], p[1]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: p[2]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.title);
infowindow.open(map, this);
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
//Ajax call
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
dataType : 'html',
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
</script>
So what I now need to do is to send an array of coordinated via the Ajax call and on success update the existing Google Map with new coordinates.
I have tried to find a documentation of this but no luck..
If someone knows a good way to do this please help.
I ended up choosing a completely different approach. Here is the code I used, which works
<script type="text/javascript">
var locations = {}; //A repository for markers (and the data from which they were contructed).
//initial dataset for markers
var locs = {
1: {
info: '11111. Some random info here',
lat: -37.8139,
lng: 144.9634
},
2: {
info: '22222. Some random info here',
lat: 46.0553,
lng: 14.5144
},
3: {
info: '33333. Some random info here',
lat: -33.7333,
lng: 151.0833
},
4: {
info: '44444. Some random info here',
lat: 27.9798,
lng: -81.731
}
};
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 1,
maxZoom: 8,
minZoom: 1,
streetViewControl: false,
center: new google.maps.LatLng(30, 30),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
function setMarkers(locObj) {
jQuery.each(locObj, function (key, loc) {
if (!locations[key] && loc.lat !== undefined && loc.lng !== undefined) {
//Marker has not yet been made (and there's enough data to create one).
//Create marker
loc.marker = new google.maps.Marker({
position: new google.maps.LatLng(loc.lat, loc.lng),
map: map
});
//Attach click listener to marker
google.maps.event.addListener(loc.marker, 'click', (function (key) {
return function () {
infowindow.setContent(locations[key].info);
infowindow.open(map, locations[key].marker);
}
})(key));
//Remember loc in the `locations` so its info can be displayed and so its marker can be deleted.
locations[key] = loc;
} else if (locations[key] && loc.remove) {
//Remove marker from map
if (locations[key].marker) {
locations[key].marker.setMap(null);
}
//Remove element from `locations`
delete locations[key];
} else if (locations[key]) {
//Update the previous data object with the latest data.
jQuery.extend(locations[key], loc);
if (loc.lat !== undefined && loc.lng !== undefined) {
//Update marker position (maybe not necessary but doesn't hurt).
locations[key].marker.setPosition(
new google.maps.LatLng(loc.lat, loc.lng));
}
//locations[key].info looks after itself.
}
});
}
setMarkers(locs); //Create markers from the initial dataset served with the document.
//ajaxObj.get(); //Start the get cycle.
// *******************
//Ajax code
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
dataType : 'html',
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
jQuery('#testdiv').html(arr[2]);
//test: simulated ajax
var testLocs = {
1: {
info: '1. New Random info and new position',
lat: -37,
lng: 124.9634
},
2: {
lat: 70,
lng: 14.5144
},
3: {
info: '3. New Random info'
},
4: {
remove: true
},
5: {
info: '55555. Added',
lat: -37,
lng: 0
}
};
setMarkers(testLocs);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
</script>
i have a magento site where my products are businesses.
I want to add a google map to the product page and need someone to help me with my code.
I can call the zip code by typing
<?php echo $_product->getpostcode() ?>
I have taken code from the internet and am trying to put it together for my site. here is the code:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var geocoder;
var map;
var address = '<?php echo $_product->getpostcode() ?>'
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}
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({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
<body onload="initialize()">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
At the moment it is using the lat long in the code. How can i change it to using the zip code?`
Maps always use co-ordinates. That how maps work. If you want to use a zipcode, you need to convert that to co-ordinates — that process is called geocoding.
You have a geocoding function in your code, which won't work at the moment because you don't have an element called address, but it can be used with a little adjustment.
You currently have a global variable called address, which contains your zipcode, so get your geocoder function to use it:
At the bottom of function initialize(), add a call to the geocoder function, passing it the global variable:
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
codeAddress(address);
}
Change that function to accept a parameter:
function codeAddress(addy) {
and then to use it:
// var address = document.getElementById('address').value;
// The above line needs to be removed; the one below amended
geocoder.geocode( { 'address': addy}, function(results, status) {
//i have working function use it.
function initialize() {
var address = "<?php echo $address?>";
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(50.317408,11.12915);
var myOptions = {
zoom: 8,
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("location-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("Address Not found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
I'm trying to do two things from the code below:
If the geocode is not successfull don't show the map (so far I've only hidden the error message.)
If it is successful only load the address and not the original latlng before reloading the address.
You'll have to excuse all the single quote marks, the javascript loads under a php echo.
Any ideas welcome, ideally I'd like to handle it in the javascript but don't mind a bit of php if needed, I'm looking to use this in a few areas of the site.
echo '
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(51.500141,-0.125195);
var address = \''.$company.', '.$address_l1.', '.$address_l2.', '.$address_l3.', '.$town.', '.$county.', '.$post_code.', '.$country.'\';
var myOptions = {
zoom: 16,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
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({
map: map,
position: results[0].geometry.location
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<div id="map_canvas"></div>
';
Move the map creation into the success function of geocode and use document.getElementById('map_canvas').style.display='block' or none to show/hide the map on fail.
I've managed to trial/error put together a working google v3 api that geocodes an address coming from the database.
Now I"m trying to accomplish two final tasks:
The map flashes the original geocode (34.05,-118.24) that is set before the api geocodes the variable I've passed to it. When I remove this lat/long, the map doesn't work at all. How can I stop the map from flashing the original lat/long before geocoding the address I've given it?
I'd like the user to be able to click the marker and get a result (i.e. "Hello World"). So far with trial and error I have not been able to successfully get the marker to be clickable.
Please help!! Thanks in advance as always.
$address, $city, $state and such are php variables coming from mysql
My google script looks like this:
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = '<?php echo $address.', '.$city.', '.$state; ?>';
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
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({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
So to make the marker clickable, you need to have an event listener on it. Also you'll want an infowindow to display your 'hello world'. This does both, add it into your initialize function.
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: 'Hello World!',
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
I would also consider doing the geocoding of your address before you create the map, so you can use results[0].geometry.location to set the map center initially.
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = '<?php echo $address.', '.$city.', '.$state; ?>';
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myOptions.center = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: 'Hello World!',
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
// just open the map at the default latlng
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
});
}