Related
I have a issue with google distance map, we have multiple locations and i want to drew map from my current location to nearest address from given multiple address and i have already created and its working fine, but i have a issue with map marker, by default its return marker point address but i want current location return default current position address and i want to customise only destination marker, when i use "suppressMarkers: true" destination marker customisation working but current position marker not return default current location, and when i use "suppressMarkers: false" both marker return default address/locations.
<script type="text/javascript">
var map,
currentPosition,
directionsDisplay,
directionsService,
destinationLatitude = 67.38,
destinationLongitude = -56.11;
jQuery(document).ready(function( $ ) {
getLocation();
});
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function getPosition(position) {
localStorage.setItem("current_latitude", position.coords.latitude);
localStorage.setItem("current_longitude", position.coords.longitude);
locSuccess(position.coords.latitude,position.coords.longitude);
}
function initializeMapAndCalculateRoute(lat, lon)
{
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
currentPosition = new google.maps.LatLng(lat, lon);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 16,
center: currentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
var currentPositionMarker = new google.maps.Marker({
position: currentPosition,
map: map,
title: "My Location"
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(currentPositionMarker, 'click', function() {
infowindow.setContent("Current position: latitude: " + lat +" longitude: " + lon);
infowindow.open(map, currentPositionMarker);
});
calculateRoute(destinationLatitude, destinationLongitude);
}
function locSuccess(latitude,longitude) {
initializeMapAndCalculateRoute(latitude,longitude);
}
function calculateRoute(targetLat, targetLon) {
var targetDestination = new google.maps.LatLng(targetLat, targetLon);
if (currentPosition != '' && targetDestination != '') {
var request = {
origin: currentPosition,
destination: targetDestination,
travelMode: google.maps.DirectionsTravelMode["DRIVING"]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setPanel(document.getElementById("directions"));
directionsDisplay.setDirections(response);
$("#outputs").show();
}
else {
$("#outputs").hide();
}
});
}
else {
$("#outputs").hide();
}
}
</script>
As per our understanding, you should use "geocode" for the current formatted address.
If you will use "suppressMarkers: true", in that case, you have to set the marker manually. Use have no issue with destination marker customization but the issue with only starting/origin marker.
So you should customize the destination marker accordingly and by using geocode get the current location formated_address and set it within your origin marker.
google.maps.event.addListener(currentPositionMarker, "click", function()
{
var point = currentPositionMarker.getPosition();
map.panTo(point);
MapGeocoder.geocode({
'latLng': currentPositionMarker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, currentPositionMarker);
}
});
});
Full Example:
<!doctype html>
<html lang="en">
<head>
<title>Google maps</title>
<style>
.subheading,.sidelinks,.timify-widget-open-button{display:none!important}
.map-container{box-shadow:0 0 0 2px #ccc;transition:300ms;display:flex;position:relative;overflow:hidden}
.map-container input{position:absolute;top:0;left:0;opacity:0;width:0}
.map-box{min-width:calc(100% - 200px);max-width:calc(100% - 200px);min-height:320px;height:calc(100vh - 340px);transition:300ms}
.city-box{list-style-type:none;padding:10px 0;width:200px;height:100%;right:0;position:absolute;margin:0;box-sizing:border-box;transition:300ms;overflow:hidden;overflow-y:auto}
.city-box li{padding:12px 12px 12px 36px;cursor:pointer;background-image:url(https://developers.google.com/maps/documentation/javascript/images/marker_greenA.png);background-repeat:no-repeat;background-size:25px auto;background-position:10px;transition:350ms}
.city-box li.active{color:#fff;background-color:black!important}
.city-box li:nth-child(even){background-color:#eee}
.map-label{position:absolute;width:24px;height:60px;right:200px;top:calc(50% - 30px);background-color:#fff;box-shadow:-3px 0 3px #cccc;z-index:2;border-radius:4px 0 0 4px;cursor:pointer;transition:300ms;display:flex;justify-content:center;align-items:center}
.map-label::before{content:'';width:10px;height:10px;margin-left:-2px;border-top:2px solid currentColor;border-right:2px solid currentColor;transform:rotate(45deg)}
.map-container input:checked ~ .map-label{right:0}
.map-container input:checked ~ .map-label::before{transform:rotate(225deg);margin-left:5px}
.map-container input:checked ~ .map-box{width:100%;min-width:100%!important;max-width:100%!important}
.map-container input:checked ~ .city-box{right:-200px}
#floating-panel{position:absolute;top:10px;left:25%;z-index:5;background-color:#fff;padding:5px;border:1px solid #999;text-align:center;font-family:"Roboto","sans-serif";line-height:30px;padding-left:10px}
.info_content{display:flex;width:100%;max-width:350px;align-items:center}
.info_content .media-thumb img{max-width:100px;margin-right:10px}
.info_content .content{display:inline-block}
.info_content h3{margin:0 0 4px 0;font-size:15px}
.info_content p{margin:0;font-size:12px;line-height:1.5}
.scroller::-webkit-scrollbar{height:12px;width:5px;background:#333}
.scroller::-webkit-scrollbar-thumb{background:#969494;-webkit-border-radius:1ex;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.75)}
.scroller::-webkit-scrollbar-corner{background:#333}
.scroller{overflow-y:scroll;scrollbar-color:#333 #969494;scrollbar-width:thin!important}
</style>
</head>
<body>
<div class="container-fluid px-0 map-container">
<div id="floating-panel">
<b>Mode of Travel: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
<input type="checkbox" id="maptoggle">
<label for="maptoggle" class="map-label maptogglemenu"></label>
<div class="map-box" id="map_canvas"></div>
<ul id="mybranches" class="city-box">
<li class="active" data-lan="28.38" data-lon="77.12" data-title="Location Title" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Delhi, India</li>
<li data-lan="12.120000" data-lon="76.680000" data-title="Location Title A" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Nanjangud, Mysore, Karnataka</li>
<li data-lan="24.879999" data-lon="74.629997" data-title="Location Title B" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Chittorgarh, Rajasthan</li>
<li data-lan="16.994444" data-lon="73.300003" data-title="Location Title C" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Ratnagiri, Maharashtra</li>
<li data-lan="19.155001" data-lon="72.849998" data-title="Location Title D" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Goregaon, Mumbai, Maharashtra</li>
<li data-lan="24.794500" data-lon="73.055000" data-title="Location Title E" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Pindwara, Rajasthan</li>
<li data-lan="21.250000" data-lon="81.629997" data-title="Location Title F" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Raipur, Chhattisgarh</li>
<li data-lan="16.166700" data-lon="74.833298" data-title="Location Title G" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Gokak, Karnataka</li>
<li data-lan="19.076090" data-lon="72.877426" data-title="Location Title H" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Mumbai, Maharashtra</li>
<li data-lan="14.167040" data-lon="75.040298" data-title="Location Title I" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Sagar, Karnataka</li>
<li data-lan="26.540457" data-lon="88.719391" data-title="Location Title J" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Jalpaiguri, West Bengal</li>
<li data-lan="24.633568" data-lon="87.849251" data-title="Location Title K" data-html="Web Site title | My location full Address" data-img="https://weneedwebsite.com/blog/assets/img/random-flags/images/67.jpg">Pakur, Jharkhand</li>
</ul>
</div>
<div id="results" style="display:none;">
<div id="directions" class="scroller px-3" style="overflow: hidden; overflow-y: auto; max-height: 300px;"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_map_api_key_here&sensor=false&libraries=geometry&v=3"></script>
<script type="text/javascript">
var map,
currentPosition,
targetPosition,
targetMarker,
infowindow,
currentLatitude,
currentLongitude,
directionsDisplay,
directionsService,
locationTitle,
locationAddress,
destinationLatitude = 49.4505682,
destinationLongitude = 11.0702432;
jQuery(document).ready(function( $ ) {
if (!localStorage.getItem("current_latitude")) {
getLocation();
}
else{
currentLatitude = localStorage.getItem("current_latitude");
currentLongitude = localStorage.getItem("current_longitude");
locSuccess(currentLatitude, currentLongitude);
}
});
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function getPosition(position) {
currentLatitude = position.coords.latitude;
currentLongitude = position.coords.longitude;
localStorage.setItem("current_latitude", currentLatitude);
localStorage.setItem("current_longitude", currentLongitude);
locSuccess(currentLongitude,currentLongitude);
}
function locSuccess(currentLatitude,currentLongitude) {
var nearestLocation = null;
var locations = [];
jQuery('ul#mybranches li').each(function(){
var location_lat = jQuery(this).attr('data-lan');
var location_lng = jQuery(this).attr('data-lon');
var location_title = jQuery(this).attr('data-title');
var location_address = jQuery(this).attr('data-html');
var location_image = jQuery(this).attr('data-img');
var p1 = new google.maps.LatLng(currentLatitude, currentLongitude);
var p2 = new google.maps.LatLng(location_lat, location_lng);
var distance = calcDistance(p1, p2) * 1000;
if ((distance * 1000) > 0) {
if (nearestLocation === null || nearestLocation.distance > distance) {
nearestLocation = {distance: location_image, mylat: currentLatitude, mylng: currentLongitude, location_lat: location_lat, location_lng: location_lng, location_title: location_title, location_address: location_address, location_image: location_image };
}
}
});
var lat = nearestLocation.location_lat;
var long = nearestLocation.location_lng;
var title = nearestLocation.location_title;
var address = nearestLocation.location_address;
var image = nearestLocation.location_image;
jQuery('#mybranches li[data-lan]').removeClass('active');
jQuery('#mybranches li[data-title="'+title+'"]').addClass('active');
initializeMapAndCalculateRoute(currentLatitude,currentLongitude,lat,long,title,address,image);
}
function initializeMapAndCalculateRoute(lat, lon, destinationLatitude, destinationLongitude, locationTitle, locationAddress,locationImage)
{
currentPosition = new google.maps.LatLng(lat, lon);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 15,
center: currentPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
MapGeocoder = new google.maps.Geocoder();
var rendererOptions = {
map: map,
suppressMarkers: true
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(map);
var currentPositionMarker = new google.maps.Marker({
position: currentPosition,
map: map,
title: "Current position"
});
infowindow = new google.maps.InfoWindow({ map: map });
google.maps.event.addListener(currentPositionMarker, "click", function() {
var point = currentPositionMarker.getPosition();
map.panTo(point);
MapGeocoder.geocode({
'latLng': currentPositionMarker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, currentPositionMarker);
}
});
});
document.getElementById("mode").addEventListener("change", () => {
calculateRoute(destinationLatitude, destinationLongitude, locationTitle, locationAddress,locationImage);
});
// calculate Route
calculateRoute(destinationLatitude, destinationLongitude, locationTitle, locationAddress,locationImage);
}
function calculateRoute(targetLat, targetLon, locationTitle, locationAddress, locationImage) {
const targetDestination = new google.maps.LatLng(targetLat, targetLon);
const selectedMode = document.getElementById("mode").value ? document.getElementById("mode").value : 'DRIVING';
if (currentPosition != '' && targetDestination != '') {
const request = {
origin: currentPosition,
destination: targetDestination,
travelMode: google.maps.TravelMode[selectedMode],
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
createMarker(targetDestination, locationTitle, locationAddress, locationImage);
directionsDisplay.setPanel(document.getElementById("directions"));
directionsDisplay.setDirections(response);
jQuery("#results").show();
}
else {
jQuery("#results").hide();
}
});
}
else {
jQuery("#results").hide();
}
}
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
function createMarker(latlng, label, html, image) {
var contentString = '<div class="info_content">' +
'<div class="media-thumb"><img src="'+image+'"/></div>' +
'<div class="content">'+
'<h3>'+label+'</h3>' +
'<p>'+html+'</p>' +
'</div>'+
'</div>';
targetMarker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
icon: 'https://developers.google.com/maps/documentation/javascript/images/marker_greenA.png',
zIndex: Math.round(latlng.lat() * -100000) << 5
});
targetMarker.myname = label;
google.maps.event.addListener(targetMarker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, targetMarker);
});
return targetMarker;
}
function clearMarkers() {
targetMarker.setMap(null);
}
jQuery(document).on('click', 'li[data-lan]', function () {
if(!currentLatitude || !currentLongitude){
currentLatitude = localStorage.getItem("current_latitude");
currentLongitude = localStorage.getItem("current_longitude");
}
jQuery('li[data-lan]').removeClass('active');
jQuery(this).addClass('active');
destinationLatitude = jQuery(this).attr('data-lan');
destinationLongitude = jQuery(this).attr('data-lon');
locationTitle = jQuery(this).attr('data-title');
locationAddress = jQuery(this).attr('data-html');
locationImage = jQuery(this).attr('data-img');
clearMarkers();
calculateRoute(destinationLatitude,destinationLongitude,locationTitle,locationAddress,locationImage);
});
jQuery(document).ready(function( $ ) {
if(localStorage.getItem('distancemapmenu') && localStorage.getItem('distancemapmenu') == 'checked'){
jQuery('#maptoggle').prop("checked", true);
}
});
jQuery(document).on('click', '.maptogglemenu', function(){
if(jQuery('#maptoggle').is(':checked')){
var value = '';
}else{
var value = 'checked';
}
localStorage.setItem('distancemapmenu', value);
});
</script>
</body>
</html>
As per screenshot Location, "Lucknow" is your default/origin location with default marker and location "Gurugram" is your customize(marker) location
I need to find all the locations near by the lat long and radius provided.I think I can achieve this by using geofence but I don't know how to proceed.I have the following data.
set of lat long and to get the location for radius within 5km for all the lat long by each.
Any one help how to start this.
Inputs I have:
lat long
33.450909, -112.073196
33.466210, -112.064620
33.451640, -112.099130
33.437160, -112.048400
33.480860, -112.082130
33.489950, -112.074700
Tried so far:
<!DOCTYPE html >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Creating a Store Locator on Google Maps</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body style="margin:0px; padding:0px;" onload="initMap()">
<div>
<label for="raddressInput">Search location:</label>
<input type="text" id="addressInput" size="15"/>
<label for="radiusSelect">Radius:</label>
<select id="radiusSelect" label="Radius">
<option value="50" selected>50 kms</option>
<option value="30">30 kms</option>
<option value="20">20 kms</option>
<option value="10">10 kms</option>
</select>
<input type="button" id="searchButton" value="Search"/>
</div>
<div><select id="locationSelect" style="width: 10%; visibility: hidden"></select></div>
<div id="map" style="width: 100%; height: 90%"></div>
<script>
var map;
var markers = [];
var infoWindow;
var locationSelect;
function initMap() {
var sydney = {lat: 33.450909, lng: -112.073196};
map = new google.maps.Map(document.getElementById('map'), {
center: sydney,
zoom: 11,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
searchButton = document.getElementById("searchButton").onclick = searchLocations;
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var id = markerNodes[i].getAttribute("id");
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name;
locationSelect.appendChild(option);
}
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 parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVD0ngfhOFs5rnww7UFyz9rN6UznOIZ1U&callback=initMap">
</script>
</body>
</html>
Using the above I can able to point single point,But what I want is to get the location around each lat long provided above radius is 5 km
If you are already using Google Maps, then I think you can try with computeDistanceBetween.
This is a short example of how to use it. You just need to eliminate those distances greater than the radius you set.
var home = ['Store', new google.maps.LatLng(29.520130, -98.415542)];
var pts = [
['Client A', new google.maps.LatLng(29.5197902, -98.3867079)],
['Client B', new google.maps.LatLng(29.5165967, -98.4235714)],
['Client C', new google.maps.LatLng(29.5198805, -98.3676648)]
];
var dist = google.maps.geometry.spherical.computeDistanceBetween;
pts.forEach(function(pt) {
console.log(home[0] + ' to ' + pt[0] + ': ' + (dist(home[1], pt[1])).toFixed(10));
});
This my script to get the latitude,longitude and place name. i can get only latitude longitude but not the place name.
<script type="text/javascript">
$(document).ready(function () {
var longitude = $('#longitude');
var latitude = $('#latitude');
var hiddenControl = '<%= inpHide.ClientID %>';
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p) {
longitude.text(p.coords.longitude);
latitude.text(p.coords.latitude);
document.getElementById(hiddenControl).value = p.coords.latitude + "," + p.coords.longitude;
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
// alert(p.coords.latitude);
var mapOptions = {
center: LatLng,
zoom: 20,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude,
});
google.maps.event.addListener(marker, "click", function (e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
var hidPlace = '<%= inpPlace.ClientID %>';
var lblplace = $('#lblplace');
var google_maps_geocoder = new google.maps.Geocoder();
google_maps_geocoder.geocode(
{ 'latLng': LatLng },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results[0]) {
lblplace.text(results[0].formatted_address);
}
}
);
});
} else {
alert('Location feature is not supported in this browser.');
}
});
</script>
<section class="content">
<script src="http://maps.google.com/maps/api/js?key=key"></script>
<label id="latitude" runat="server"></label>
<br />
<label id="longitude" runat="server"></label>
<br />
<div id="dvMap" style="width: 500px; height: 500px" runat="server" visible="false"></div>
<input id="inpHide" type="hidden" runat="server" />
<input id="locHide" type="hidden" runat="server" />
<label id="lblplace" runat="server"></label>
<input id="inpPlace" type="hidden" runat="server" />
<br />
</section>
asp.net c# code behind i can get the inphide as latitude and longitude, but the lblplace is returning null value every time. please support me to find where i am doing the wrong.
with the hidden field
var hidPlace = '<%= inpPlace.ClientID %>';
var lblplace ='<%= locHide.ClientID %>'
var google_maps_geocoder = new google.maps.Geocoder();
google_maps_geocoder.geocode(
{ 'latLng': LatLng },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results[0]) {
document.getElementById(hidPlace).value=results[0].formatted_address;
}
}
);
I am facing a problem. My map is not loading on IOS but when I run it on android device it displays nothing and throws an error in log
E/Web Console﹕ Uncaught ReferenceError: google is not defined at line no 64
I am using a store locator API
Store Locator API
The maps works fine when i test it on ripple emulate and IOS device, But When it comes towards android it stuck.
My code is
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&callback=storeLocator" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
$.fn.storeLocator = function (options) {
var settings = $.extend({
'mapDiv': 'map',
'listDiv': 'list',
'formID': 'user-location',
'pinColor': 'fe7569',
'startPinColor': '66bd4a',
'pinTextColor': '000000',
'storeLimit': 10,
'distanceAlert': 60,
'xmlLocation': 'data/wholecar.xml',
'addressErrorMsg': 'Please enter valid WA address address or postcode',
'googleDistanceMatrixDestinationLimit': 50,
'defaultLat': 115.857469,
'defaultLng': -31.953004,
'defaultLocationName': 'Perth, WA'
}, options);
return this.each(function () {
var $this = $(this);
// global array of shop objects
var _locationset = new Array();
var geocoder;
// Calculate distances from passed in origin to all locations in the [_locationset] array
// using Google Maps Distance Matrix Service https://developers.google.com/maps/documentation/javascript/reference#DistanceMatrixService
var GeoCodeCalc = {};
GeoCodeCalc.CalcDistanceGoogle = function (origin, callback) {
var destCoordArr = new Array();
var subFunctionTokens = [];
$.each(_locationset, function (ix, loc) {
destCoordArr.push(loc.LatLng);
});
for (var i = 0; i < destCoordArr.length; i = i + settings.googleDistanceMatrixDestinationLimit) { // Google Distance Matrix allows up to 25 destinations to be passed in
var tempArr = destCoordArr.slice(i, Math.min(i + settings.googleDistanceMatrixDestinationLimit));
subFunctionTokens.push(this.CallGoogleDistanceMatrix(i, origin, tempArr));
}
$.when.apply($, subFunctionTokens)
.then(function () {
callback(true);
});
};
GeoCodeCalc.CallGoogleDistanceMatrix = function (startIndex, origin, destinations) {
var token = $.Deferred();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function (response, status) {
if (response && response.rows.length) {
var results = response.rows[0].elements;
$.each(results, function (j, val) {
if (results[j].status != "ZERO_RESULTS") {
_locationset[startIndex + j].Distance = GoogleMapDistanceTextToNumber(results[j].distance.text);
}
});
token.resolve();
}
});
return token.promise();
};
// Converts "123.45 mi" into 123.45
function GoogleMapDistanceTextToNumber(str) {
return Number(str.replace(/[^0-9.]/g, ""));
}
// removes Google Maps URL unfriendly chars from a string
function formatGoogleMapUrlString(str) {
return str.replace("&", "%26").replace(" ", "+");
}
//Geocode function for the origin location
geocoder = new google.maps.Geocoder();
function GoogleGeocode() {
this.geocode = function (address, callbackFunction) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result = {};
result.latitude = results[0].geometry.location.lat();
result.longitude = results[0].geometry.location.lng();
result.formatted_address = results[0].formatted_address;
result.address_components = results[0].address_components;
callbackFunction(result);
} else {
handleError("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
};
this.geocodeLatLng = function (LatLng, callbackFunction) {
geocoder.geocode({ 'location': LatLng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
callbackFunction(results[0]);
} else {
handleError("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
};
}
//Process form input
$(function () {
$(document).on('submit', '#' + settings.formID, function (e) {
$("#lblError").html("");
//Stop the form submission
e.preventDefault();
//Get the user input and use it
var userinput = $('form').serialize();
userinput = userinput.replace("address=", "");
if (userinput == "") {
handleError(settings.addressErrorMsg);
}
var g = new GoogleGeocode();
var address = userinput;
g.geocode(address, function (data) {
if (data != null) {
showAddress(data);
mapping(data.latitude, data.longitude);
} else {
//Unable to geocode
handleError(settings.addressErrorMsg);
}
});
//Replace spaces in user input
userinput = formatGoogleMapUrlString(userinput);
});
});
$(document).ready(function () {
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
//map.setCenter(pos);
var g = new GoogleGeocode();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
g.geocodeLatLng(latlng, function (address) {
if (address) {
showAddress(address);
} else {
//Unable to geocode
handleNoGeolocation('Error: Unable to geocode address');
}
});
// do the mapping stuff
mapping(position.coords.latitude, position.coords.longitude);
}, function () {
handleNoGeolocation("Tracking of location was not allowed.");
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
});
function showAddress(address) {
$("#lblAddress").html(address.formatted_address);
// find a postcode and show it in the address textbox
$.each(address.address_components, function (i, val) {
if (val.types[0] == "postal_code") {
$("#address").val(val.short_name);
return false; // breaks the each() loop
}
});
}
function handleNoGeolocation(error) {
if (error) {
var content = error;
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
handleError(content + " Using default location.");
mapping(settings.defaultLat, settings.defaultLng);
$("#lblAddress").html(settings.defaultLocationName);
}
function handleError(error) {
$("#lblError").html(error);
}
//Now all the mapping stuff
function mapping(orig_lat, orig_lng) {
$(function () {
//Parse xml with jQuery
$.ajax({
type: "GET",
url: settings.xmlLocation,
dataType: "xml",
success: function (xml) {
_locationset = new Array();
$(xml).find('Placemark').each(function (i) {
var shop = {
Name: $(this).find('name').text(),
//Take the lat lng from the user, geocoded above
LatLng: new google.maps.LatLng(
$(this).find('coordinates').text().split(",")[1],
$(this).find('coordinates').text().split(",")[0]),
Description: $(this).find('description').text(),
Marker: null,
Distance: null
};
_locationset.push(shop);
});
// Calc Distances from user's location
GeoCodeCalc.CalcDistanceGoogle(new google.maps.LatLng(orig_lat, orig_lng), function (success) {
if (!success) { //something went wrong
handleError("Unable to calculate distances at this time");
}
else {
//Sort the multi-dimensional array numerically
_locationset.sort(function (a, b) {
return ((a.Distance < b.Distance) ? -1 : ((a.Distance > b.Distance) ? 1 : 0));
});
// take "N" closest shops
_locationset = _locationset.slice(0, settings.storeLimit);
//Check the closest marker
if (_locationset[0].Distance > settings.distanceAlert) {
handleError("Unfortunately, we currently don't have nearest location details for your area.");
}
//Create the map with jQuery
$(function () {
var orig_LatLng = new google.maps.LatLng(orig_lat, orig_lng);
//Google maps settings
var myOptions = {
center: orig_LatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(settings.mapDiv), myOptions);
//Create one infowindow to fill later
var infowindow = new google.maps.InfoWindow();
//Add user location marker
var marker = createMarker(orig_LatLng, "0", settings.startPinColor);
marker.setAnimation(google.maps.Animation.DROP);
var bounds = new google.maps.LatLngBounds();
bounds.extend(orig_LatLng);
$("#" + settings.listDiv).empty();
$(_locationset).each(function (i, location) {
bounds.extend(location.LatLng);
letter = String.fromCharCode("A".charCodeAt(0) + i);
if (((location.Distance * 1.69)<=30)&&(location.Distance != null))
{
location.Marker = createMarker(location.LatLng, letter, settings.pinColor);
create_infowindow(location);
listClick(letter, location);
}
});
// zoom in/out to show all markers
map.fitBounds(bounds);
function listClick(letter, shop) {
$('<li />').html("<div class=\"list-details\"><div class=\"list-content\">"
+ "<div class=\"list-label\">" + letter + "<\/div>"
+ "<div class=\"loc-name\">" + shop.Name + "<\/div> <div class=\"loc-addr\">" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div class=\"loc-addr2\"><i>approx. " + Math.round(shop.Distance * 1.69) + " kilometers</i><\/div>" : "")
+ "<div class=\"loc-web\"><a href=\"http://maps.google.co.uk/maps?saddr="
+ formatGoogleMapUrlString($("#address").val()) + "+%40" + orig_lat + "," + orig_lng
+ "&daddr=" + formatGoogleMapUrlString(shop.Name) + "+%40" + shop.LatLng.lat() + "," + shop.LatLng.lng()
+ "&hl=en" + "\" target=\"_blank\">>Get directions</a><\/div><\/div><\/div>")
.click(function () {
create_infowindow(shop, "left");
}).appendTo("#" + settings.listDiv);
};
//Custom marker function - aplhabetical
function createMarker(point, letter, pinColor) {
//Set up pin icon with the Google Charts API for all of our markers
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + letter + "|" + pinColor + "|" + settings.pinTextColor,
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34));
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
//Create the markers
return new google.maps.Marker({
position: point,
map: map,
icon: pinImage,
shadow: pinShadow,
draggable: false
});
};
//Infowindows
function create_infowindow(shop, listLocation) {
var formattedAddress = "<div class=\"infoWindow\"><b>" + shop.Name + "<\/b>"
+ "<div>" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div><i>" + Math.round(shop.Distance * 1.69) + " kilometers<\/i><\/div><\/div>" : "<\/div>");
//Opens the infowindow when list item is clicked
if (listLocation == "left") {
infowindow.setContent(formattedAddress);
infowindow.open(shop.Marker.get(settings.mapDiv), shop.Marker);
}
//Opens the infowindow when the marker is clicked
else {
google.maps.event.addListener(shop.Marker, 'click', function () {
infowindow.setContent(formattedAddress);
infowindow.open(shop.Marker.get(settings.mapDiv), shop.Marker);
})
}
};
});
}
});
}
});
});
}
});
};})(jQuery);
</script>
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
$('#map-container').storeLocator();
try{
var pageid = $(".MainContent").attr('id');
var title = $(".MainContent").attr('data-title');
//alert(title);
//alert("pageshow"+pageid);
if(title != undefined)
Analytic.sendScreenName(title);
}catch(e){
//alert(e);
}
}
</script>
<!DOCTYPE html>
<div class="address">
<label>
We have identified your location as:
</label>
<label id="lblAddress">
</label>.
<label>Or enter your location here.</label>
</div>
<form id="user-location" class="well form-search" method="post" action="#">
<div id="form-input">
<input type="text" id="address" name="address" value="" class="input-medium search-query" />
</div>
<div id="submit-btn">
<button type="submit" data-theme="b" name="submit" class="btn btn-warning" data-mini="true" value="submit-value">Submit</button></div>
<div class="error">
<label id="lblError"></label>
</div>
</form>
</div>
<div id="map-container">
<div id="loc-list">
<div id="loc-list-wrapper">
<ul id="list">
</ul>
</div>
</div>
<div id="map">
</div>
</div>
</div></div>
Try using this:
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
On Device Ready Load google DomListener.
Something like this - google.maps.event.addDomListener(window, 'load');
Also check you have added google maps script -
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false" ></script>
and you have allowed all intents in config file:
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
My first aplication about distance matrix to calculate distance. The first If load script are text box auto input by postcode after identify my ISP location. That textbox can input address or postcode to put my realy location after klick button submit query. Marker for my addres or my postcode show. And then with Parse xml with jQuery can show distance every destination.
Now I wil make change how to put my location by mouse over and then If klick in map I will get latlng and location address to process distance matrik AS origin.
This my First code: ( THANKS BEFORE )
(function ($) {
$.fn.storeLocator = function (options) {
var settings = $.extend({
'mapDiv': 'map',
'listDiv': 'list',
'formID': 'user-location',
'pinColor': 'fe7569',
'startPinColor': '66bd4a',
'pinTextColor': '000000',
'storeLimit': 10,
'distanceAlert': 500,
'xmlLocation': 'data/suplier.xml',
'addressErrorMsg': 'Please enter valid address address or postcode',
'googleDistanceMatrixDestinationLimit': 25,
'defaultLat': 49.719330,
'defaultLng': -2.214539,
'defaultLocationName': 'Northampton, United Kingdom'
}, options);
return this.each(function () {
var $this = $(this);
// global array of shop objects
var _locationset = new Array();
var geocoder;
// Calculate distances from passed in origin to all locations in the [_locationset] array
// using Google Maps Distance Matrix Service https://developers.google.com/maps/documentation/javascript/reference#DistanceMatrixService
var GeoCodeCalc = {};
GeoCodeCalc.CalcDistanceGoogle = function (origin, callback) {
var destCoordArr = new Array();
var subFunctionTokens = [];
$.each(_locationset, function (ix, loc) {
destCoordArr.push(loc.LatLng);
});
for (var i = 0; i < destCoordArr.length; i = i + settings.googleDistanceMatrixDestinationLimit) { // Google Distance Matrix allows up to 25 destinations to be passed in
var tempArr = destCoordArr.slice(i, Math.min(i + settings.googleDistanceMatrixDestinationLimit));
subFunctionTokens.push(this.CallGoogleDistanceMatrix(i, origin, tempArr));
}
$.when.apply($, subFunctionTokens)
.then(function () {
callback(true);
});
};
GeoCodeCalc.CallGoogleDistanceMatrix = function (startIndex, origin, destinations) {
var token = $.Deferred();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: destinations,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
}, function (response, status) {
if (response && response.rows.length) {
var results = response.rows[0].elements;
$.each(results, function (j, val) {
if (results[j].status != "ZERO_RESULTS") {
_locationset[startIndex + j].Distance = GoogleMapDistanceTextToNumber(results[j].distance.text);
}
});
token.resolve();
}
});
return token.promise();
};
// Converts "123.45 mi" into 123.45
function GoogleMapDistanceTextToNumber(str) {
return Number(str.replace(/[^0-9.]/g, ""));
}
// removes Google Maps URL unfriendly chars from a string
function formatGoogleMapUrlString(str) {
return str.replace("&", "%26").replace(" ", "+");
}
//Geocode function for the origin location
geocoder = new google.maps.Geocoder();
function GoogleGeocode() {
this.geocode = function (address, callbackFunction) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result = {};
result.latitude = results[0].geometry.location.lat();
result.longitude = results[0].geometry.location.lng();
result.formatted_address = results[0].formatted_address;
result.address_components = results[0].address_components;
callbackFunction(result);
} else {
handleError("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
};
this.geocodeLatLng = function (LatLng, callbackFunction) {
geocoder.geocode({ 'location': LatLng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
callbackFunction(results[0]);
} else {
handleError("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
};
}
//Process form input
$(function () {
$(document).on('submit', '#' + settings.formID, function (e) {
$("#lblError").html("");
//Stop the form submission
e.preventDefault();
//Get the user input and use it
var userinput = $('form').serialize();
userinput = userinput.replace("address=", "");
if (userinput == "") {
handleError(settings.addressErrorMsg);
}
var g = new GoogleGeocode();
var address = userinput;
g.geocode(address, function (data) {
if (data != null) {
showAddress(data);
mapping(data.latitude, data.longitude);
} else {
//Unable to geocode
handleError(settings.addressErrorMsg);
}
});
//Replace spaces in user input
userinput = formatGoogleMapUrlString(userinput);
});
});
$(document).ready(function () {
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
//map.setCenter(pos);
var g = new GoogleGeocode();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
g.geocodeLatLng(latlng, function (address) {
if (address) {
showAddress(address);
} else {
//Unable to geocode
handleNoGeolocation('Error: Unable to geocode address');
}
});
// do the mapping stuff
mapping(position.coords.latitude, position.coords.longitude);
}, function () {
handleNoGeolocation("Tracking of location was not allowed.");
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
});
function showAddress(address) {
$("#lblAddress").html(address.formatted_address);
// find a postcode and show it in the address textbox
$.each(address.address_components, function (i, val) {
if (val.types[0] == "postal_code") {
$("#address").val(val.short_name);
return false; // breaks the each() loop
}
});
}
function handleNoGeolocation(error) {
if (error) {
var content = error;
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
handleError(content + " Using default location.");
mapping(settings.defaultLat, settings.defaultLng);
$("#lblAddress").html(settings.defaultLocationName);
}
function handleError(error) {
$("#lblError").html(error);
}
//Now all the mapping stuff
function mapping(orig_lat, orig_lng) {
$(function () {
//Parse xml with jQuery
$.ajax({
type: "GET",
url: settings.xmlLocation,
dataType: "xml",
success: function (xml) {
_locationset = new Array();
$(xml).find('Placemark').each(function (i) {
var shop = {
Name: $(this).find('name').text(),
//Take the lat lng from the user, geocoded above
LatLng: new google.maps.LatLng(
$(this).find('coordinates').text().split(",")[1],
$(this).find('coordinates').text().split(",")[0]),
Description: $(this).find('description').text(),
Ongkir:$(this).find('ongkir').text(),
Muat:$(this).find('muat').text(),
Item:$(this).find('item').text(),
Kirim: (($(this).find('item').text())/($(this).find('muat').text())),
Marker: null,
Distance: null
};
_locationset.push(shop);
});
// Calc Distances from user's location
GeoCodeCalc.CalcDistanceGoogle(new google.maps.LatLng(orig_lat, orig_lng), function (success) {
if (!success) { //something went wrong
handleError("Unable to calculate distances at this time");
}
else {
//Sort the multi-dimensional array numerically
_locationset.sort(function (a, b) {
return ((a.Distance < b.Distance) ? -1 : ((a.Distance > b.Distance) ? 1 : 0));
});
// take "N" closest shops
_locationset = _locationset.slice(0, settings.storeLimit);
//Check the closest marker
if (_locationset[0].Distance > settings.distanceAlert) {
handleError("Unfortunately, our closest location is more than " + settings.distanceAlert + " miles away.");
}
//Create the map with jQuery
$(function () {
var orig_LatLng = new google.maps.LatLng(orig_lat, orig_lng);
//Google maps settings
var myOptions = {
center: orig_LatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(settings.mapDiv), myOptions);
//Create one infowindow to fill later
var infowindow = new google.maps.InfoWindow();
//Add user location marker
var marker = createMarker(orig_LatLng, "0", settings.startPinColor);
marker.setAnimation(google.maps.Animation.DROP);
var bounds = new google.maps.LatLngBounds();
bounds.extend(orig_LatLng);
$("#" + settings.listDiv).empty();
$(_locationset).each(function (i, location) {
bounds.extend(location.LatLng);
letter = String.fromCharCode("A".charCodeAt(0) + i);
location.Marker = createMarker(location.LatLng, letter, settings.pinColor);
create_infowindow(location);
listClick(letter, location);
});
// zoom in/out to show all markers
map.fitBounds(bounds);
function listClick(letter, shop) {
$('<li />').html("<div class=\"list-details\"><div class=\"list-content\">"
+ "<div class=\"list-label\">" + letter + "<\/div>"
+ "<div class=\"loc-name\">" + shop.Name + "<\/div> <div class=\"loc-addr\">" + shop.Description + "<\/div>Muat " + shop.Muat + " <div class=\"loc-addr\">Rp." + shop.Ongkir + " per Km<\/div> "
+ (shop.Distance ? "<div class=\"loc-addr2\"><i>Jarak Tempuh. "+Math.ceil(shop.Distance*1.6) + "Km</i><\/br>"+ Math.ceil(shop.Kirim) + " Kali Angkut <\/br><\/br>ONGKOS KIRIM <input type=\"text\" readonly=\"readonly\" size=\"20\" name=\"jarak\" value=\"Rp. "+Math.ceil((shop.Distance * shop.Ongkir*1.6) * Math.ceil(shop.Kirim)) + "\" /><\/div>" : "")
+ "<div class=\"loc-web\"><a href=\"http://maps.google.co.uk/maps?saddr="
+ formatGoogleMapUrlString($("#address").val()) + "+%40" + orig_lat + "," + orig_lng
+ "&daddr=" + formatGoogleMapUrlString(shop.Name) + "+%40" + shop.LatLng.lat() + "," + shop.LatLng.lng()
+ "&hl=en" + "\" target=\"_blank\">>Get directions</a><\/div><\/div><\/div>")
.click(function () {
create_infowindow(shop, "left");
}).appendTo("#" + settings.listDiv);
};
//Custom marker function - aplhabetical
function createMarker(point, letter, pinColor) {
//Set up pin icon with the Google Charts API for all of our markers
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + letter + "|" + pinColor + "|" + settings.pinTextColor,
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34));
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
//Create the markers
return new google.maps.Marker({
position: point,
map: map,
icon: pinImage,
shadow: pinShadow,
draggable: false
});
};
//Infowindows
function create_infowindow(shop, listLocation) {
var formattedAddress = "<div class=\"infoWindow\"><b>" + shop.Name + "<\/b>"
+ "<div>" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div><i>" + shop.Distance + " miles<\/i><\/div><\/div>" : "<\/div>");
//Opens the infowindow when list item is clicked
if (listLocation == "left") {
infowindow.setContent(formattedAddress);
infowindow.open(shop.Marker.get(settings.mapDiv), shop.Marker);
}
//Opens the infowindow when the marker is clicked
else {
google.maps.event.addListener(shop.Marker, 'click', function () {
infowindow.setContent(formattedAddress);
infowindow.open(shop.Marker.get(settings.mapDiv), shop.Marker);
})
}
};
});
}
});
}
});
});
}
});
};
})(jQuery);
I'm not sure to understand your question, but if what you want is to be able to add a marker by clicking the map and then lunch the distance calculation what you have to do is to add a click event listener to the map and do what you have to do there.
Consider the following exemple (change YOUR_GOOGLE_MAPS_API_KEY for your own key in order to be able to run the demo):
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&sensor=false">
</script>
<style type="text/css">
html
{
height: 100%;
}
body
{
height: 100%;
margin: 0;
padding: 0;
}
#map-container
{
height: 100%;
width: 100%;
min-width:500px;
min-height:300px;
}
</style>
</head>
<body>
<div id="map-container">
Div map
</div>
<script type="text/javascript" language="javascript">
var map;
$(document).ready(function () {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map($("#map-container")[0], mapOptions);
google.maps.event.addListener(map, 'click', function (mouseEvent) {
var origin = mouseEvent.latLng;
var marker = new google.maps.Marker({ position: origin });
marker.setMap(map);
//console.log("map clicked");
// your logic ......
// returnFromCalcDistanceGoogle(origin, callback);
// your logic ......
});
});
function returnFromCalcDistanceGoogle() {
// your logic ......
}
</script>
</body>
</html>
If this is not what your trying to do, please clarify your question.
Like that Mr.sabotero . .. but i will use this in my first application that. When I klick the map LatLng can input in my textbox with id="address" to submit query. Before the textbox with id="address" just work if input by addres and postcode. Now I want LatLang can input and process in textbox with id="address"
<div id="form-input">
<label for="address">
Masukan Lokasi Anda</label>
<input type="text" id="address" name="address" value="" class="input-medium search-query" />
</div>
<div id="submit-btn">
<input type="submit" id="submit" name="submit" class="btn btn-warning" /></div>
input postscode or address
Klick submit Query
Marker Origin show with color green
NOW I wont,
1. klick map
2. textbox get latlng or addres
3. submit query