1

I have a static Google Map like this:

<img alt="Map" height="135" src="http://maps.google.com/maps/api/staticmap?scale=2&amp;center=45.504358%2C-73.553712&amp;language=en&amp;zoom=15&amp;markers=scale%3A2%7Cshadow%3Afalse%7Cicon%3Ahttp%3A%2F%2Fyelp-images.s3.amazonaws.com%2Fassets%2Fmap-markers%2Fannotation_64x86.png%7C45.504358%2C-73.553712&amp;client=gme-yelp&amp;sensor=false&amp;size=286x135&amp;signature=nM1FwS0L3z_VgK2ljaRcJf11HxA=" width="286">

How it is possible to get just the part in a variable

var lat = 45.504358;
var lng = -73.553712;

I tried:

var mapSrc = $(pageDetails).find('[alt="Map"]').prop('src');
var card_Latitude = mapSrc.match(/center=(.*?)%2C-/i)[1];
user4037798
  • 91
  • 1
  • 1
  • 4

5 Answers5

1

There's a generic function for grabbing query string parameters with JS (see this answer):

How can I get query string values in JavaScript?

So it's just like this:

function getParameterByName(name, url) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(url);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Then in your particular case you just call it like this (assuming your img is named "img"):

var center = getParameterByName("center",document.getElementById("img").src).split(",");

alert("lat: " + center[0] + " long: " + center[1]);

See this fiddle:

http://jsfiddle.net/soemdjah/1

Community
  • 1
  • 1
aquinas
  • 23,318
  • 5
  • 58
  • 81
0
center=(\d+(?:\.\d+)?)%2C(-?\d+(?:\.\d+)?)

Try this.See demo.

http://regex101.com/r/iO1uK1/9

vks
  • 67,027
  • 10
  • 91
  • 124
0

You can use base javascript RegExp :

var matches = new RegExp('center=(\\d+\\.?\\d*)%2C(-?\\d+\\.?\\d*)').exec(mapSrc);
if (matches) {
    var lat = matches[1];
    var lng = matches[2];
}
Sileno
  • 11
  • 3
0

You can split your src by parameters and then split by key / value pair of each parameter in order to find the latitude and logitude value within the src property. Eg:

var mapSrc = $(pageDetails).find('[alt="Map"]').prop('src');
jQuery(mapSrc.split("&"), function(index, value) {
  var keyPair = value.split("=");
  if (keyPair[0] == "center") {
    var lat = decodeURIComponent(keyPair[1]).split(",")[0];
    var lng = decodeURIComponent(keyPair[1]).split(",")[1]
  }
});

Using above, no regex is needed at all. However, if you want to still use regex for this task, here is the pattern: 'center=([^%]+)%2C-([^&]+)'

Eder
  • 1,874
  • 17
  • 34
0

One more solution:

;center=( [.\d]+)%?[0-9A-Z]+([-.\d+]+)

Demo
http://regex101.com/r/qK0jJ1/2

Sivasakthi Jayaraman
  • 4,724
  • 3
  • 17
  • 27